Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix autocorrection for Rails/IndexBy and Rails/IndexWith when map { ... }.to_h is enclosed in another block #1406

Merged
merged 1 commit into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -107,6 +107,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
Loading