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.



6269
6270
6271
6272
# File 'lib/syntax_tree/node.rb', line 6269

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

Instance Attribute Details

#keywordObject (readonly)

String

the keyword associated with this conditional



6264
6265
6266
# File 'lib/syntax_tree/node.rb', line 6264

def keyword
  @keyword
end

#nodeObject (readonly)

If | Unless

the node that is being formatted



6267
6268
6269
# File 'lib/syntax_tree/node.rb', line 6267

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
# File 'lib/syntax_tree/node.rb', line 6274

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