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

Extended by:
Macros
Included in:
CaseCorrector, ConditionalAssignment, IfCorrector, TernaryCorrector
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 =
'='
END_ALIGNMENT =
'Layout/EndAlignment'
ALIGN_WITH =
'EnforcedStyleAlignWith'
KEYWORD =
'keyword'

Instance Method Summary collapse

Instance Method Details

#end_with_eq?(sym) ⇒ Boolean

Returns:

  • (Boolean)


64
65
66
# File 'lib/rubocop/cop/style/conditional_assignment.rb', line 64

def end_with_eq?(sym)
  sym.to_s.end_with?(EQUAL)
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.



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

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.



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

def expand_when_branches(when_branches)
  when_branches.map(&:body)
end

#indent(cop, source) ⇒ Object

rubocop:enable Metrics/AbcSize



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

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

#lhs(node) ⇒ Object

rubocop:disable Metrics/AbcSize



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 37

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, :or_asgn
    "#{node.children[0].source} #{node.loc.operator.source} "
  when :casgn
    lhs_for_casgn(node)
  when *ConditionalAssignment::VARIABLE_ASSIGNMENT_TYPES
    "#{node.children[0]} = "
  else
    node.source
  end
end

#tail(branch) ⇒ Object



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

def tail(branch)
  branch.begin_type? ? Array(branch).last : branch
end