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 =
'EnforcedStyleAlignWith'.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.



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

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.



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

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

#indent(cop, source) ⇒ Object



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

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

rubocop:disable Metrics/MethodLength



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

def lhs(node) # rubocop:disable Metrics/MethodLength
  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



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

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