Skip to content

Commit

Permalink
Fix incorrect Style/HashSyntax autocorrection for assignment methods
Browse files Browse the repository at this point in the history
In Ruby 3.1 and above, code like:

```ruby
object.attr = {foo: foo}
                    ^^^ Omit the hash value.
pass
```

was incorrectly autocorrected to:

```ruby
object.attr({foo:})
pass
```

The autocorrected code is valid Ruby, but is semantically different.
This may and will lead to subtle bugs in user codebases.
  • Loading branch information
gsamokovarov committed Mar 7, 2023
1 parent 1f7094d commit 693796e
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11673](https://github.com/rubocop/rubocop/pull/11673): Fix incorrect `Style/HashSyntax` autocorrection for assignment methods. ([@gsamokovarov][])
1 change: 1 addition & 0 deletions lib/rubocop/cop/mixin/hash_shorthand_syntax.rb
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ def def_node_that_require_parentheses(node)
last_pair = node.parent.pairs.last
return unless last_pair.key.source == last_pair.value.source
return unless (dispatch_node = find_ancestor_method_dispatch_node(node))
return if dispatch_node.assignment_method?
return if dispatch_node.parenthesized?
return if dispatch_node.parent && parentheses?(dispatch_node.parent)
return if last_expression?(dispatch_node) && !method_dispatch_as_argument?(dispatch_node)
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/style/hash_syntax_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1154,6 +1154,19 @@ def do_something
RUBY
end

it 'registers an offense when expression follows attribute assignment' do
expect_offense(<<~RUBY)
object.attr = {foo: foo}
^^^ Omit the hash value.
pass
RUBY

expect_correction(<<~RUBY)
object.attr = {foo:}
pass
RUBY
end

it 'registers an offense when expression follows multiple assignments' do
expect_offense(<<~RUBY)
foo = bar = do_stuff arg, opt1: opt1,
Expand Down

0 comments on commit 693796e

Please sign in to comment.