Skip to content

Commit

Permalink
Merge pull request #1406 from eugeneius/index_by_index_with_enclosing…
Browse files Browse the repository at this point in the history
…_block

Fix autocorrection for `Rails/IndexBy` and `Rails/IndexWith` when `map { ... }.to_h` is enclosed in another block
  • Loading branch information
koic authored Jan 6, 2025
2 parents 7edc744 + ece1454 commit 88b9dc5
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog/fix_index_by_index_with_enclosing_block.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1406](https://github.com/rubocop/rubocop-rails/pull/1406): Fix autocorrection for `Rails/IndexBy` and `Rails/IndexWith` when `map { ... }.to_h` is enclosed in another block. ([@franzliedke][], [@eugeneius][])
6 changes: 3 additions & 3 deletions lib/rubocop/cop/mixin/index_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,9 @@ def self.from_to_h(node, match)
end

def self.from_map_to_h(node, match)
strip_trailing_chars = 0

unless node.parent&.block_type?
if node.block_literal?
strip_trailing_chars = 0
else
map_range = node.children.first.source_range
node_range = node.source_range
strip_trailing_chars = node_range.end_pos - map_range.end_pos
Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/rails/index_by_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,27 @@
end
end

context 'when enclosed in another block' do
it 'registers an offense for `map { ... }.to_h`' do
expect_offense(<<~RUBY)
wrapping do
x.map do |el|
^^^^^^^^^^^^^ Prefer `index_by` over `map { ... }.to_h`.
[el.to_sym, el]
end.to_h
end
RUBY

expect_correction(<<~RUBY)
wrapping do
x.index_by do |el|
el.to_sym
end
end
RUBY
end
end

it 'registers an offense for `Hash[map { ... }]`' do
expect_offense(<<~RUBY)
Hash[x.map { |el| [el.to_sym, el] }]
Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/rails/index_with_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,27 @@
end
end

context 'when enclosed in another block' do
it 'registers an offense for `map { ... }.to_h`' do
expect_offense(<<~RUBY)
wrapping do
x.map do |el|
^^^^^^^^^^^^^ Prefer `index_with` over `map { ... }.to_h`.
[el, el.to_sym]
end.to_h
end
RUBY

expect_correction(<<~RUBY)
wrapping do
x.index_with do |el|
el.to_sym
end
end
RUBY
end
end

it 'registers an offense for `Hash[map { ... }]`' do
expect_offense(<<~RUBY)
Hash[x.map { |el| [el, el.to_sym] }]
Expand Down

0 comments on commit 88b9dc5

Please sign in to comment.