Module: SyntaxTree::Parentheses

Defined in:
lib/syntax_tree/node.rb

Overview

If you have a modifier statement (for instance a modifier if statement or a modifier while loop) there are times when you need to wrap the entire statement in parentheses. This occurs when you have something like:

foo[:foo] =
  if bar?
    baz
  end

Normally we would shorten this to an inline version, which would result in:

foo[:foo] = baz if bar?

but this actually has different semantic meaning. The first example will result in a nil being inserted into the hash for the :foo key, whereas the second example will result in an empty hash because the if statement applies to the entire assignment.

We can fix this in a couple of ways. We can use the then keyword, as in:

foo[:foo] = if bar? then baz end

But this isn’t used very often. We can also just leave it as is with the multi-line version, but for a short predicate and short value it looks verbose. The last option and the one used here is to add parentheses on both sides of the expression, as in:

foo[:foo] = (baz if bar?)

This approach maintains the nice conciseness of the inline version, while keeping the correct semantic meaning.

Constant Summary collapse

NODES =
[
  Args,
  Assign,
  Assoc,
  Binary,
  Call,
  Defined,
  MAssign,
  OpAssign
].freeze

Class Method Summary collapse

Class Method Details

.break(q) ⇒ Object



6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
# File 'lib/syntax_tree/node.rb', line 6587

def self.break(q)
  return yield unless NODES.include?(q.parent.class)

  q.text("(")
  q.indent do
    q.breakable("")
    yield
  end
  q.breakable("")
  q.text(")")
end

.flat(q) ⇒ Object



6579
6580
6581
6582
6583
6584
6585
# File 'lib/syntax_tree/node.rb', line 6579

def self.flat(q)
  return yield unless NODES.include?(q.parent.class)

  q.text("(")
  yield
  q.text(")")
end