Class: RuboCop::Cop::Style::ParallelAssignment::AssignmentSorter

Inherits:
Object
  • Object
show all
Extended by:
NodePattern::Macros
Includes:
TSort
Defined in:
lib/rubocop/cop/style/parallel_assignment.rb

Overview

Helper class necessitated by silly design of TSort prior to Ruby 2.1 Newer versions have a better API, but that doesn’t help us

Instance Method Summary collapse

Methods included from NodePattern::Macros

def_node_matcher, def_node_search, node_search, node_search_all, node_search_body, node_search_first

Constructor Details

#initialize(assignments) ⇒ AssignmentSorter

Returns a new instance of AssignmentSorter.



127
128
129
# File 'lib/rubocop/cop/style/parallel_assignment.rb', line 127

def initialize(assignments)
  @assignments = assignments
end

Instance Method Details

#accesses?(rhs, lhs) ⇒ Boolean

‘lhs` is an assignment method call like `obj.attr=` or `ary=`. Does `rhs` access the same value which is assigned by `lhs`?

Returns:

  • (Boolean)


151
152
153
154
155
156
157
158
159
160
# File 'lib/rubocop/cop/style/parallel_assignment.rb', line 151

def accesses?(rhs, lhs)
  if lhs.method_name == :[]=
    matching_calls(rhs, lhs.receiver, :[]).any? do |args|
      args == lhs.method_args
    end
  else
    access_method = lhs.method_name.to_s.chop.to_sym
    matching_calls(rhs, lhs.receiver, access_method).any?
  end
end

#tsort_each_child(assignment) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/rubocop/cop/style/parallel_assignment.rb', line 135

def tsort_each_child(assignment)
  # yield all the assignments which must come after `assignment`
  # (due to dependencies on the previous value of the assigned var)
  my_lhs, _my_rhs = *assignment

  @assignments.each do |other|
    _other_lhs, other_rhs = *other
    if ((var = var_name(my_lhs)) && uses_var?(other_rhs, var)) ||
       (my_lhs.asgn_method_call? && accesses?(other_rhs, my_lhs))
      yield other
    end
  end
end

#tsort_each_nodeObject



131
132
133
# File 'lib/rubocop/cop/style/parallel_assignment.rb', line 131

def tsort_each_node
  @assignments.each { |a| yield a }
end