Skip to content

Commit

Permalink
Fix an incorrect auto-correct for Style/HashConversion
Browse files Browse the repository at this point in the history
This PR fixes the following incorrect auto-correct for `Style/HashConversion`
when `Hash[]` as a method argument without parentheses.

```console
% cat example.rb
do_something Hash[a: b, c: d], 42

% bundle exec rubocop --only Style/HashConversion -a
(snip)

Inspecting 1 file
C

Offenses:

example.rb:1:14: C: [Corrected] Style/HashConversion: Prefer literal
hash to Hash[key: value, ...].
do_something Hash[a: b, c: d], 42
             ^^^^^^^^^^^^^^^^

1 file inspected, 1 offense detected, 1 offense corrected
```

## Before

Auto-corrected to invalid syntax.

```ruby
% cat example.rb
do_something {a: b, c: d}, 42

% ruby -c example.rb
example.rb:1: syntax error, unexpected ':', expecting '}'
do_something {a: b, c: d}, 42
```

## After

Auto-corrected to valid syntax.

```ruby
% cat example.rb
do_something({a: b, c: d}, 42)
```
  • Loading branch information
koic authored and bbatsov committed Apr 19, 2021
1 parent c53803b commit 9c36847
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
@@ -0,0 +1 @@
* [#9712](https://github.com/rubocop/rubocop/pull/9712): Fix an incorrect auto-correct for `Style/HashConversion` when `Hash[]` as a method argument without parentheses. ([@koic][])
3 changes: 3 additions & 0 deletions lib/rubocop/cop/style/hash_conversion.rb
Expand Up @@ -84,6 +84,9 @@ def use_zip_method_without_argument?(first_argument)
def register_offense_for_hash(node, hash_argument)
add_offense(node, message: MSG_LITERAL_HASH_ARG) do |corrector|
corrector.replace(node, "{#{hash_argument.source}}")

parent = node.parent
add_parentheses(parent, corrector) if parent&.send_type? && !parent.parenthesized?
end
end

Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/style/hash_conversion_spec.rb
Expand Up @@ -34,6 +34,28 @@
RUBY
end

it 'reports different offense for hash argument Hash[] as a method argument with parentheses' do
expect_offense(<<~RUBY)
do_something(Hash[a: b, c: d], 42)
^^^^^^^^^^^^^^^^ Prefer literal hash to Hash[key: value, ...].
RUBY

expect_correction(<<~RUBY)
do_something({a: b, c: d}, 42)
RUBY
end

it 'reports different offense for hash argument Hash[] as a method argument without parentheses' do
expect_offense(<<~RUBY)
do_something Hash[a: b, c: d], 42
^^^^^^^^^^^^^^^^ Prefer literal hash to Hash[key: value, ...].
RUBY

expect_correction(<<~RUBY)
do_something({a: b, c: d}, 42)
RUBY
end

it 'reports different offense for empty Hash[]' do
expect_offense(<<~RUBY)
Hash[]
Expand Down

0 comments on commit 9c36847

Please sign in to comment.