Skip to content

Commit

Permalink
[Fix rubocop#9845] Fix Style/QuotedSymbols for hash-rocket hashes.
Browse files Browse the repository at this point in the history
  • Loading branch information
dvandersluis committed Jun 2, 2021
1 parent 6a681fa commit b292109
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
1 change: 1 addition & 0 deletions 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][])
7 changes: 6 additions & 1 deletion lib/rubocop/cop/style/quoted_symbols.rb
Expand Up @@ -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
Expand All @@ -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)
Expand Down
38 changes: 38 additions & 0 deletions spec/rubocop/cop/style/quoted_symbols_spec.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit b292109

Please sign in to comment.