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.



6837
6838
6839
6840
# File 'lib/syntax_tree.rb', line 6837

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

Instance Attribute Details

#keywordObject (readonly)

String

the keyword associated with this conditional



6832
6833
6834
# File 'lib/syntax_tree.rb', line 6832

def keyword
  @keyword
end

#nodeObject (readonly)

If | Unless

the node that is being formatted



6835
6836
6837
# File 'lib/syntax_tree.rb', line 6835

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
# File 'lib/syntax_tree.rb', line 6842

def format(q)
  # 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?
    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