diff --git a/changelog/fix_an_incorrect_autocorrect_style_hash_syntax.md b/changelog/fix_an_incorrect_autocorrect_style_hash_syntax.md new file mode 100644 index 000000000000..7e101f865833 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_style_hash_syntax.md @@ -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][]) diff --git a/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb b/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb index 651af331fddb..b2c888d85bc4 100644 --- a/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb +++ b/lib/rubocop/cop/mixin/hash_shorthand_syntax.rb @@ -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 diff --git a/spec/rubocop/cop/style/hash_syntax_spec.rb b/spec/rubocop/cop/style/hash_syntax_spec.rb index 48c32cb2caab..6c2ab359b064 100644 --- a/spec/rubocop/cop/style/hash_syntax_spec.rb +++ b/spec/rubocop/cop/style/hash_syntax_spec.rb @@ -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