Skip to content

Commit 4ea096f

Browse files
committed
Fix autocorrection error with nested index offenses
1 parent 529b8d3 commit 4ea096f

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1483](https://github.com/rubocop/rubocop-rails/pull/1483): Fix autocorrection error when `Rails/IndexWith` has nested offenses. ([@lovro-bikic][])

lib/rubocop/cop/mixin/index_method.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,13 @@ def handle_possible_offense(node, match, match_desc)
132132
add_offense(
133133
node, message: "Prefer `#{new_method_name}` over `#{match_desc}`."
134134
) do |corrector|
135+
next if part_of_ignored_node?(node)
136+
135137
correction = prepare_correction(node)
136138
execute_correction(corrector, node, correction)
137139
end
140+
141+
ignore_node(node)
138142
end
139143

140144
def extract_captures(match)

spec/rubocop/cop/rails/index_with_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -325,6 +325,28 @@
325325
end
326326
end
327327
end
328+
329+
context 'with nested offenses' do
330+
it 'registers offenses and autocorrects' do
331+
expect_offense(<<~RUBY)
332+
x.each_with_object({}) do |el, h|
333+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_with` over `each_with_object`.
334+
h[el] = el.each_with_object({}) do |inner_el, inner_h|
335+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_with` over `each_with_object`.
336+
inner_h[inner_el] = foo(inner_el)
337+
end
338+
end
339+
RUBY
340+
341+
expect_correction(<<~RUBY)
342+
x.index_with do |el|
343+
el.each_with_object({}) do |inner_el, inner_h|
344+
inner_h[inner_el] = foo(inner_el)
345+
end
346+
end
347+
RUBY
348+
end
349+
end
328350
end
329351

330352
context 'when using Rails 5.2 or older', :rails52 do

0 commit comments

Comments
 (0)