Module: RuboCop::Cop::Style::ConditionalAssignmentHelper

Included in:
CaseCorrector, ConditionalAssignment, IfCorrector, TernaryCorrector, UnlessCorrector
Defined in:
lib/rubocop/cop/style/conditional_assignment.rb

Overview

Helper module to provide common methods to classes needed for the ConditionalAssignment Cop.

Constant Summary collapse

EQUAL =
'='.freeze

Instance Method Summary collapse

Instance Method Details

#correct_branches(corrector, branches) ⇒ Object



28
29
30
31
32
33
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 28

def correct_branches(corrector, branches)
  branches.each do |branch|
    *_, assignment = *branch
    corrector.replace(branch.source_range, assignment.source)
  end
end

#expand_elses(branch) ⇒ Object

elsif branches show up in the node as an else. We need to recursively iterate over all else branches and consider all but the last node an elsif branch and consider the last node the actual else branch.



16
17
18
19
20
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 16

def expand_elses(branch)
  elsif_branches = expand_elsif(branch)
  else_branch = elsif_branches.any? ? elsif_branches.pop : branch
  [elsif_branches, else_branch]
end

#expand_when_branches(when_branches) ⇒ Object

when nodes contain the entire branch including the condition. We only need the contents of the branch, not the condition.



24
25
26
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 24

def expand_when_branches(when_branches)
  when_branches.map { |branch| branch.children[1] }
end

#lhs(node) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 39

def lhs(node)
  case node.type
  when :send
    lhs_for_send(node)
  when :op_asgn
    "#{node.children[0].source} #{node.children[1]}= "
  when :and_asgn
    "#{node.children[0].source} &&= "
  when :or_asgn
    "#{node.children[0].source} ||= "
  when :casgn
    "#{node.children[1]} = "
  when *ConditionalAssignment::VARIABLE_ASSIGNMENT_TYPES
    "#{node.children[0]} = "
  else
    node.source
  end
end

#tail(branch) ⇒ Object



35
36
37
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 35

def tail(branch)
  branch.begin_type? ? [*branch].last : branch
end