Skip to content

Commit

Permalink
[Fix #9513] Fix an incorrect auto-correct for Style/HashConversion
Browse files Browse the repository at this point in the history
Fixes #9513.

This PR fixes an incorrect auto-correct for `Style/HashConversion`
when using hash argument `Hash[]`.
  • Loading branch information
koic authored and bbatsov committed Feb 13, 2021
1 parent 2d3e1bc commit 7e89008
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
1 change: 1 addition & 0 deletions changelog/fix_incorrect_autocorrect_for_hash_conversion.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#9513](https://github.com/rubocop-hq/rubocop/issues/9513): Fix an incorrect auto-correct for `Style/HashConversion` when using hash argument `Hash[]`. ([@koic][])
16 changes: 11 additions & 5 deletions lib/rubocop/cop/style/hash_conversion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ class HashConversion < Base
extend AutoCorrector

MSG_TO_H = 'Prefer ary.to_h to Hash[ary].'
MSG_LITERAL = 'Prefer literal hash to Hash[arg1, arg2, ...].'
MSG_LITERAL_MULTI_ARG = 'Prefer literal hash to Hash[arg1, arg2, ...].'
MSG_LITERAL_HASH_ARG = 'Prefer literal hash to Hash[key: value, ...].'
MSG_SPLAT = 'Prefer array_of_pairs.to_h to Hash[*array].'
RESTRICT_ON_SEND = %i[[]].freeze

Expand All @@ -44,20 +45,25 @@ def on_send(node)
private

def single_argument(node)
if node.arguments.first.splat_type?
first_argument = node.first_argument
if first_argument.hash_type?
add_offense(node, message: MSG_LITERAL_HASH_ARG) do |corrector|
corrector.replace(node, "{#{first_argument.source}}")
end
elsif first_argument.splat_type?
add_offense(node, message: MSG_SPLAT)
else
add_offense(node, message: MSG_TO_H) do |corrector|
corrector.replace(node, "#{node.arguments.first.source}.to_h")
corrector.replace(node, "#{first_argument.source}.to_h")
end
end
end

def multi_argument(node)
if node.arguments.count.odd?
add_offense(node, message: MSG_LITERAL)
add_offense(node, message: MSG_LITERAL_MULTI_ARG)
else
add_offense(node, message: MSG_LITERAL) do |corrector|
add_offense(node, message: MSG_LITERAL_MULTI_ARG) do |corrector|
corrector.replace(node, args_to_hash(node.arguments))
end
end
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/style/hash_conversion_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@
RUBY
end

it 'reports different offense for hash argument Hash[]' do
expect_offense(<<~RUBY)
Hash[a: b, c: d]
^^^^^^^^^^^^^^^^ Prefer literal hash to Hash[key: value, ...].
RUBY

expect_correction(<<~RUBY)
{a: b, c: d}
RUBY
end

it 'reports different offense for empty Hash[]' do
expect_offense(<<~RUBY)
Hash[]
Expand Down

0 comments on commit 7e89008

Please sign in to comment.