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



5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
# File 'lib/syntax_tree/node.rb', line 5206

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