Skip to content

Commit

Permalink
[Fix rubocop#9940] Fix an incorrect auto-correct for `Style/HashTrans…
Browse files Browse the repository at this point in the history
…formValues`

Fixes rubocop#9940.

This PR fixes an incorrect auto-correct for `Style/HashTransformValues`
when value is a hash literal for `_.to_h{...}`.
  • Loading branch information
koic committed Jul 19, 2021
1 parent 3907e07 commit 867c9b2
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 1 deletion.
@@ -0,0 +1 @@
* [#9940](https://github.com/rubocop/rubocop/issues/9940): Fix an incorrect auto-correct for `Style/HashTransformValues` when value is a hash literal for `_.to_h{...}`. ([@koic][])
7 changes: 6 additions & 1 deletion lib/rubocop/cop/mixin/hash_transform_method.rb
Expand Up @@ -175,7 +175,12 @@ 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.loc.expression.source)
body_source = transforming_body_expr.loc.expression.source
if transforming_body_expr.hash_type? && !transforming_body_expr.braces?
body_source = "{ #{body_source} }"
end

corrector.replace(block_node.body, body_source)
end
end
end
Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/style/hash_transform_values_spec.rb
Expand Up @@ -211,6 +211,28 @@
RUBY
end

it 'register and corrects an offense _.to_h{...} when value is a hash literal and is enclosed in braces' do
expect_offense(<<~RUBY)
{a: 1, b: 2}.to_h { |key, val| [key, { value: val }] }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `to_h {...}`.
RUBY

expect_correction(<<~RUBY)
{a: 1, b: 2}.transform_values { |val| { value: val } }
RUBY
end

it 'register and corrects an offense _.to_h{...} when value is a hash literal and is not enclosed in braces' do
expect_offense(<<~RUBY)
{a: 1, b: 2}.to_h { |key, val| [key, value: val] }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `transform_values` over `to_h {...}`.
RUBY

expect_correction(<<~RUBY)
{a: 1, b: 2}.transform_values { |val| { value: val } }
RUBY
end

it 'does not flag `_.to_h{...}` when both key & value are transformed' do
expect_no_offenses(<<~RUBY)
x.to_h { |k, v| [k.to_sym, foo(v)] }
Expand Down

0 comments on commit 867c9b2

Please sign in to comment.