Class: SyntaxTree::ConditionalFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/syntax_tree.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.



6439
6440
6441
6442
# File 'lib/syntax_tree.rb', line 6439

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

Instance Attribute Details

#keywordObject (readonly)

String

the keyword associated with this conditional



6434
6435
6436
# File 'lib/syntax_tree.rb', line 6434

def keyword
  @keyword
end

#nodeObject (readonly)

If | Unless

the node that is being formatted



6437
6438
6439
# File 'lib/syntax_tree.rb', line 6437

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
# File 'lib/syntax_tree.rb', line 6444

def format(q)
  statements = node.statements
  break_format = ->(force:) do
    q.text("#{keyword} ")
    q.nest(keyword.length + 1) { q.format(node.predicate) }

    unless statements.empty?
      q.indent do
        q.breakable(force: force)
        q.format(statements)
      end
    end

    if node.consequent
      q.breakable(force: force)
      q.format(node.consequent)
    end

    q.breakable(force: force)
    q.text("end")
  end

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