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 #9940] Fix an incorrect auto-correct for Style/HashTransformValues #9941

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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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