123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::CaseCorrector

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 case statements.

Class Method Summary

Class Method Details

.correct(corrector, cop, node)

[ GitHub ]

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

def correct(corrector, cop, node)
  when_branches, else_branch = extract_tail_branches(node)

  corrector.insert_before(node, lhs(else_branch))
  correct_branches(corrector, when_branches)
  replace_branch_assignment(corrector, else_branch)

  corrector.insert_before(node.loc.end, indent(cop, lhs(else_branch)))
end

.extract_branches(case_node) (private)

[ GitHub ]

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

def extract_branches(case_node)
  when_branches = if case_node.case_type?
                    expand_when_branches(case_node.when_branches)
                  else
                    expand_when_branches(case_node.in_pattern_branches)
                  end

  [when_branches, case_node.else_branch]
end

.extract_tail_branches(node) (private)

[ GitHub ]

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

def extract_tail_branches(node)
  when_branches, else_branch = extract_branches(node)
  when_branches.map! { |branch| tail(branch) }
  [when_branches, tail(else_branch)]
end

.move_assignment_inside_condition(corrector, node)

[ GitHub ]

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

def move_assignment_inside_condition(corrector, node)
  column = node.source_range.column
  condition = node.send_type? ? node.last_argument : node.expression
  assignment = assignment(node)

  corrector.remove(assignment)

  extract_branches(condition).flatten.each do |branch|
    move_branch_inside_condition(corrector, branch, condition, assignment, column)
  end
end

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

[ GitHub ]

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

def move_branch_inside_condition(corrector, branch, condition, assignment, column)
  branch_assignment = tail(branch)
  corrector.insert_before(branch_assignment, assignment.source)

  remove_whitespace_in_branches(corrector, branch, condition, column)

  parent_keyword = branch.parent.loc.keyword
  corrector.remove_preceding(parent_keyword, parent_keyword.column - column)
end