Skip to content

Commit

Permalink
Merge pull request #1405 from eugeneius/index_with_hash_literal_witho…
Browse files Browse the repository at this point in the history
…ut_braces

Fix autocorrection for `Rails/IndexWith` when the value is a hash literal without braces
  • Loading branch information
koic authored Jan 6, 2025
2 parents 1126163 + 6a05c6f commit 7edc744
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_index_with_hash_literal_without_braces.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1405](https://github.com/rubocop/rubocop-rails/pull/1405): Fix autocorrection for `Rails/IndexWith` when the value is a hash literal without braces. ([@koic][], [@eugeneius][])
5 changes: 4 additions & 1 deletion lib/rubocop/cop/mixin/index_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,10 @@ def set_new_arg_name(transformed_argname, corrector)
end

def set_new_body_expression(transforming_body_expr, corrector)
corrector.replace(block_node.body, transforming_body_expr.source)
body_source = transforming_body_expr.source
body_source = "{ #{body_source} }" if transforming_body_expr.hash_type? && !transforming_body_expr.braces?

corrector.replace(block_node.body, body_source)
end
end
end
Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/rails/index_with_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,32 @@
end
end

context 'when the value is a hash literal with braces' do
it 'registers an offense for `to_h { ... }`' do
expect_offense(<<~RUBY)
x.map { |el| [el, { value: el }] }.to_h
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_with` over `map { ... }.to_h`.
RUBY

expect_correction(<<~RUBY)
x.index_with { |el| { value: el } }
RUBY
end
end

context 'when the value is a hash literal without braces' do
it 'registers an offense for `to_h { ... }`' do
expect_offense(<<~RUBY)
x.map { |el| [el, value: el] }.to_h
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `index_with` over `map { ... }.to_h`.
RUBY

expect_correction(<<~RUBY)
x.index_with { |el| { value: el } }
RUBY
end
end

context 'when to_h is not called on the result' do
it 'does not register an offense for `map { ... }.to_h`' do
expect_no_offenses('x.map { |el| [el, el.to_sym] }')
Expand Down

0 comments on commit 7edc744

Please sign in to comment.