Class: SyntaxTree::ConditionalFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree/node.rb

Overview

Formats an If or Unless node.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(keyword, node) ⇒ ConditionalFormatter

Returns a new instance of ConditionalFormatter.



5255
5256
5257
5258
# File 'lib/syntax_tree/node.rb', line 5255

def initialize(keyword, node)
  @keyword = keyword
  @node = node
end

Instance Attribute Details

#keywordObject (readonly)

String

the keyword associated with this conditional



5250
5251
5252
# File 'lib/syntax_tree/node.rb', line 5250

def keyword
  @keyword
end

#nodeObject (readonly)

If | Unless

the node that is being formatted



5253
5254
5255
# File 'lib/syntax_tree/node.rb', line 5253

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
# File 'lib/syntax_tree/node.rb', line 5260

def format(q)
  # If we can transform this node into a ternary, then we're going to print
  # a special version that uses the ternary operator if it fits on one line.
  if Ternaryable.call(q, node)
    format_ternary(q)
    return
  end

  # If the predicate of the conditional contains an assignment (in which
  # case we can't know for certain that that assignment doesn't impact the
  # statements inside the conditional) then we can't use the modifier form
  # and we must use the block form.
  if ContainsAssignment.call(node.predicate)
    format_break(q, force: true)
    return
  end

  if node.consequent || node.statements.empty? || contains_conditional?
    q.group { format_break(q, force: true) }
  else
    q.group do
      q
        .if_break { format_break(q, force: false) }
        .if_flat do
          Parentheses.flat(q) do
            q.format(node.statements)
            q.text(" #{keyword} ")
            q.format(node.predicate)
          end
        end
    end
  end
end