Skip to content

Commit

Permalink
[Fix rubocop#12312] Fix an incorrect autocorrect for Style/HashSyntax
Browse files Browse the repository at this point in the history
Fixes rubocop#12312.

This PR fixes an incorrect autocorrect for `Style/HashSyntax`
when braced hash key and value are the same and it is used in `if`...`else`.
  • Loading branch information
koic committed Oct 26, 2023
1 parent 36f62b6 commit e8a63b0
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12312](https://github.com/rubocop/rubocop/issues/12312): Fix an incorrect autocorrect for `Style/HashSyntax` when braced hash key and value are the same and it is used in `if`...`else`. ([@koic][])
25 changes: 14 additions & 11 deletions lib/rubocop/cop/mixin/hash_shorthand_syntax.rb
Original file line number Diff line number Diff line change
Expand Up @@ -48,18 +48,21 @@ def on_pair(node)

def register_offense(node, message, replacement) # rubocop:disable Metrics/AbcSize
add_offense(node.value, message: message) do |corrector|
if (def_node = def_node_that_require_parentheses(node))
last_argument = def_node.last_argument
if last_argument.nil? || !last_argument.hash_type?
next corrector.replace(node, replacement)
end

white_spaces = range_between(def_node.selector.end_pos,
def_node.first_argument.source_range.begin_pos)
corrector.replace(white_spaces, '(')
corrector.insert_after(last_argument, ')') if node == last_argument.pairs.last
end
corrector.replace(node, replacement)

next unless (def_node = def_node_that_require_parentheses(node))

last_argument = def_node.last_argument
if last_argument.nil? || !last_argument.hash_type?
next corrector.replace(node, replacement)
end

white_spaces = range_between(def_node.selector.end_pos,
def_node.first_argument.source_range.begin_pos)
next if node.parent.braces?

corrector.replace(white_spaces, '(')
corrector.insert_after(last_argument, ')') if node == last_argument.pairs.last
end
end

Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/style/hash_syntax_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -938,6 +938,25 @@
RUBY
end

it 'registers and corrects an offense when braced hash key and value are the same and it is used in `if`...`else`' do
expect_offense(<<~RUBY)
if condition
template % {value: value}
^^^^^ Omit the hash value.
else
do_something
end
RUBY

expect_correction(<<~RUBY)
if condition
template % {value:}
else
do_something
end
RUBY
end

it 'registers and corrects an offense when hash key and hash value are the same and it in the method body' do
expect_offense(<<~RUBY)
def do_something
Expand Down

0 comments on commit e8a63b0

Please sign in to comment.