diff --git a/changelog/fix_fix_stylequotedsymbols_for_hashrocket.md b/changelog/fix_fix_stylequotedsymbols_for_hashrocket.md new file mode 100644 index 00000000000..b8e83e6a3a7 --- /dev/null +++ b/changelog/fix_fix_stylequotedsymbols_for_hashrocket.md @@ -0,0 +1 @@ +* [#9845](https://github.com/rubocop/rubocop/issues/9845): Fix `Style/QuotedSymbols` for hash-rocket hashes. ([@dvandersluis][]) diff --git a/lib/rubocop/cop/style/quoted_symbols.rb b/lib/rubocop/cop/style/quoted_symbols.rb index e1f196e2a7c..d6c61571bea 100644 --- a/lib/rubocop/cop/style/quoted_symbols.rb +++ b/lib/rubocop/cop/style/quoted_symbols.rb @@ -58,7 +58,7 @@ def on_sym(node) private def autocorrect(corrector, node) - str = if hash_key?(node) + str = if hash_colon_key?(node) # strip quotes correct_quotes(node.source[1..-2]) else @@ -69,6 +69,11 @@ def autocorrect(corrector, node) corrector.replace(node, str) end + def hash_colon_key?(node) + # Is the node a hash key with the colon style? + hash_key?(node) && node.parent.colon? + end + def correct_quotes(str) if style == :single_quotes to_string_literal(str) diff --git a/spec/rubocop/cop/style/quoted_symbols_spec.rb b/spec/rubocop/cop/style/quoted_symbols_spec.rb index e6089267af3..0348173c8c0 100644 --- a/spec/rubocop/cop/style/quoted_symbols_spec.rb +++ b/spec/rubocop/cop/style/quoted_symbols_spec.rb @@ -112,6 +112,25 @@ { 'a': value } RUBY end + + context 'hash with hashrocket style' do + it 'accepts properly quoted symbols' do + expect_no_offenses(<<~RUBY) + { :'a' => value } + RUBY + end + + it 'corrects wrong quotes' do + expect_offense(<<~RUBY) + { :"a" => value } + ^^^^ Prefer single-quoted symbols when you don't need string interpolation or special symbols. + RUBY + + expect_correction(<<~RUBY) + { :'a' => value } + RUBY + end + end end shared_examples_for 'enforce double quotes' do @@ -193,6 +212,25 @@ :"a" RUBY end + + context 'hash with hashrocket style' do + it 'accepts properly quoted symbols' do + expect_no_offenses(<<~RUBY) + { :"a" => value } + RUBY + end + + it 'corrects wrong quotes' do + expect_offense(<<~RUBY) + { :'a' => value } + ^^^^ Prefer double-quoted symbols unless you need single quotes to avoid extra backslashes for escaping. + RUBY + + expect_correction(<<~RUBY) + { :"a" => value } + RUBY + end + end end context 'configured with `same_as_string_literals`' do