From 6a05c6fe7528ebb13f2eba4b50fb42ed30f207cd Mon Sep 17 00:00:00 2001 From: Eugene Kenny Date: Sun, 5 Jan 2025 11:07:28 +0000 Subject: [PATCH] Fix autocorrection for `Rails/IndexWith` when the value is a hash literal without braces --- ..._index_with_hash_literal_without_braces.md | 1 + lib/rubocop/cop/mixin/index_method.rb | 5 +++- spec/rubocop/cop/rails/index_with_spec.rb | 26 +++++++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_index_with_hash_literal_without_braces.md diff --git a/changelog/fix_index_with_hash_literal_without_braces.md b/changelog/fix_index_with_hash_literal_without_braces.md new file mode 100644 index 0000000000..db2a335a8c --- /dev/null +++ b/changelog/fix_index_with_hash_literal_without_braces.md @@ -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][]) diff --git a/lib/rubocop/cop/mixin/index_method.rb b/lib/rubocop/cop/mixin/index_method.rb index 9174cebb35..8fefa5177c 100644 --- a/lib/rubocop/cop/mixin/index_method.rb +++ b/lib/rubocop/cop/mixin/index_method.rb @@ -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 diff --git a/spec/rubocop/cop/rails/index_with_spec.rb b/spec/rubocop/cop/rails/index_with_spec.rb index ea49367af7..9f3d783eb0 100644 --- a/spec/rubocop/cop/rails/index_with_spec.rb +++ b/spec/rubocop/cop/rails/index_with_spec.rb @@ -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] }')