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
END_ALIGNMENT =
'Lint/EndAlignment'.freeze
ALIGN_WITH =
'AlignWith'.freeze
KEYWORD =
'keyword'.freeze

Instance Method Summary collapse

Instance Method Details

#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.



19
20
21
22
23
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 19

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.



27
28
29
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 27

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

#indent(cop, source) ⇒ Object



54
55
56
57
58
59
60
61
62
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 54

def indent(cop, source)
  if cop.config[END_ALIGNMENT] &&
     cop.config[END_ALIGNMENT][ALIGN_WITH] &&
     cop.config[END_ALIGNMENT][ALIGN_WITH] == KEYWORD
    ' ' * source.length
  else
    ''
  end
end

#lhs(node) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 35

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



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

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