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



5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
# File 'lib/syntax_tree/node.rb', line 5107

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