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.



6339
6340
6341
6342
# File 'lib/syntax_tree/node.rb', line 6339

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

Instance Attribute Details

#keywordObject (readonly)

String

the keyword associated with this conditional



6334
6335
6336
# File 'lib/syntax_tree/node.rb', line 6334

def keyword
  @keyword
end

#nodeObject (readonly)

If | Unless

the node that is being formatted



6337
6338
6339
# File 'lib/syntax_tree/node.rb', line 6337

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
# File 'lib/syntax_tree/node.rb', line 6344

def format(q)
  if node.modifier?
    statement = node.statements.body[0]

    if ContainsAssignment.call(statement) || q.parent.is_a?(In)
      q.group { format_flat(q) }
    else
      q.group do
        q
          .if_break { format_break(q, force: false) }
          .if_flat { format_flat(q) }
      end
    end
  else
    # 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
end