Module: SyntaxTree::Ternaryable

Defined in:
lib/syntax_tree/node.rb

Overview

In order for an ‘if` or `unless` expression to be shortened to a ternary, there has to be one and only one consequent clause which is an Else. Both the body of the main node and the body of the Else node must have only one statement, and that statement must not be on the denied list of potential statements.

Class Method Summary collapse

Class Method Details

.call(q, node) ⇒ Object



5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
# File 'lib/syntax_tree/node.rb', line 5194

def call(q, node)
  case q.parents.take(2)[1]
  in Paren[contents: Statements[body: [node]]]
    # If this is a conditional inside of a parentheses as the only
    # content, then we don't want to transform it into a ternary.
    # Presumably the user wanted it to be an explicit conditional because
    # there are parentheses around it. So we'll just leave it in place.
    false
  else
    # Otherwise, we're going to check the conditional for certain cases.
    case node
    in predicate: Assign | Command | CommandCall | MAssign | OpAssign
      false
    in predicate: Not[parentheses: false]
      false
    in {
         statements: { body: [truthy] },
         consequent: Else[statements: { body: [falsy] }] }
      ternaryable?(truthy) && ternaryable?(falsy)
    else
      false
    end
  end
end