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

Inherits:
Object
  • Object
show all
Extended by:
ConditionalAssignmentHelper, ConditionalCorrectorHelper
Defined in:
lib/rubocop/cop/style/conditional_assignment.rb

Overview

Corrector to correct conditional assignment in ternary conditions.

Constant Summary

Constants included from ConditionalAssignmentHelper

ConditionalAssignmentHelper::ALIGN_WITH, ConditionalAssignmentHelper::END_ALIGNMENT, ConditionalAssignmentHelper::EQUAL, ConditionalAssignmentHelper::KEYWORD

Class Method Summary collapse

Methods included from ConditionalCorrectorHelper

assignment, correct_branches, remove_whitespace_in_branches

Methods included from ConditionalAssignmentHelper

expand_elses, expand_when_branches, indent, lhs, tail

Class Method Details

.correct(node) ⇒ Object



421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 421

def correct(node)
  condition, if_branch, else_branch = *node
  _variable, *_operator, if_rhs = *if_branch
  _else_variable, *_operator, else_rhs = *else_branch
  condition = condition.source
  if_rhs = if_rhs.source
  else_rhs = else_rhs.source

  ternary = "#{condition} ? #{if_rhs} : #{else_rhs}"
  if if_branch.send_type? && if_branch.method_name != :[]=
    ternary = "(#{ternary})"
  end
  correction = "#{lhs(if_branch)}#{ternary}"

  lambda do |corrector|
    corrector.replace(node.source_range, correction)
  end
end

.move_assignment_inside_condition(node) ⇒ Object



440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 440

def move_assignment_inside_condition(node)
  *_var, rhs = *node
  condition, = *rhs if rhs.begin_type? && rhs.children.size == 1
  assignment = assignment(node)
  _condition, if_branch, else_branch = *(condition || rhs)

  lambda do |corrector|
    corrector.remove(assignment)
    if rhs.begin_type?
      corrector.remove(rhs.loc.begin)
      corrector.remove(rhs.loc.end)
    end
    corrector.insert_before(if_branch.loc.expression,
                            assignment.source)
    corrector.insert_before(else_branch.loc.expression,
                            assignment.source)
  end
end