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.



6969
6970
6971
6972
# File 'lib/syntax_tree.rb', line 6969

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

Instance Attribute Details

#keywordObject (readonly)

String

the keyword associated with this conditional



6964
6965
6966
# File 'lib/syntax_tree.rb', line 6964

def keyword
  @keyword
end

#nodeObject (readonly)

If | Unless

the node that is being formatted



6967
6968
6969
# File 'lib/syntax_tree.rb', line 6967

def node
  @node
end

Instance Method Details

#format(q) ⇒ Object



6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
# File 'lib/syntax_tree.rb', line 6974

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