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.



6777
6778
6779
6780
# File 'lib/syntax_tree.rb', line 6777

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

Instance Attribute Details

#keywordObject (readonly)

String

the keyword associated with this conditional



6772
6773
6774
# File 'lib/syntax_tree.rb', line 6772

def keyword
  @keyword
end

#nodeObject (readonly)

If | Unless

the node that is being formatted



6775
6776
6777
# File 'lib/syntax_tree.rb', line 6775

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
# File 'lib/syntax_tree.rb', line 6782

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 [Assign, MAssign, OpAssign].include?(node.predicate.class)
    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