123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::TernaryCorrector

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Inherits: Object
Defined in: lib/rubocop/cop/style/conditional_assignment.rb

Overview

Corrector to correct conditional assignment in ternary conditions.

Class Method Summary

Class Method Details

.correct(corrector, node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 503

def correct(corrector, node)
  corrector.replace(node, correction(node))
end

.correction(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 521

def correction(node)
  "#{lhs(node.if_branch)}#{ternary(node)}"
end

.element_assignment?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 534

def element_assignment?(node)
  node.send_type? && !node.method?(:[]=)
end

.extract_branches(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 538

def extract_branches(node)
  rhs = node.send_type? ? node.last_argument : node.expression
  condition = rhs.children.first if rhs.begin_type? && rhs.children.one?
  _condition, if_branch, else_branch = *(condition || rhs)

  [if_branch, else_branch]
end

.move_assignment_inside_condition(corrector, node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 507

def move_assignment_inside_condition(corrector, node)
  rhs = node.send_type? ? node.last_argument : node.expression
  if_branch, else_branch = extract_branches(node)
  assignment = assignment(node)

  remove_parentheses(corrector, rhs) if Util.parentheses?(rhs)
  corrector.remove(assignment)

  move_branch_inside_condition(corrector, if_branch, assignment)
  move_branch_inside_condition(corrector, else_branch, assignment)
end

.move_branch_inside_condition(corrector, branch, assignment) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 551

def move_branch_inside_condition(corrector, branch, assignment)
  corrector.insert_before(branch, assignment.source)
end

.remove_parentheses(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 546

def remove_parentheses(corrector, node)
  corrector.remove(node.loc.begin)
  corrector.remove(node.loc.end)
end

.ternary(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 525

def ternary(node)
  _variable, *_operator, if_rhs = *node.if_branch
  _else_variable, *_operator, else_rhs = *node.else_branch

  expr = "#{node.condition.source} ? #{if_rhs.source} : #{else_rhs.source}"

  element_assignment?(node.if_branch) ? "(#{expr})" : expr
end