Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an incorrect autocorrect for Rails/EnumHash #142

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

* [#120](https://github.com/rubocop-hq/rubocop-rails/issues/120): Fix message for `Rails/SaveBang` when the save is in the body of a conditional. ([@jas14][])
* [#131](https://github.com/rubocop-hq/rubocop-rails/pull/131): Fix an incorrect autocorrect for `Rails/Presence` when using `[]` method. ([@forresty][])
* [#142](https://github.com/rubocop-hq/rubocop-rails/pull/142): Fix an incorrect autocorrect for `Rails/EnumHash` when using nested constants. ([@koic][])

## 2.3.2 (2019-09-01)

Expand Down
10 changes: 4 additions & 6 deletions lib/rubocop/cop/rails/enum_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,11 @@ def on_send(node)
end

def autocorrect(node)
range = node.loc.expression
hash = node
.children
.each_with_index
.map { |elem, index| [elem.children.first, index] }.to_h
hash = node.children.each_with_index.map do |elem, index|
"#{elem.source} => #{index}"
end.join(', ')

->(corrector) { corrector.replace(range, hash.to_s) }
->(corrector) { corrector.replace(node.loc.expression, "{#{hash}}") }
end

private
Expand Down
24 changes: 23 additions & 1 deletion spec/rubocop/cop/rails/enum_hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,29 @@
RUBY

expect_correction(<<~RUBY)
enum status: {:old=>0, :"very active"=>1, "is archived"=>2, 42=>3}
enum status: {:old => 0, :"very active" => 1, "is archived" => 2, 42 => 3}
RUBY
end

it 'autocorrects constants' do
expect_offense(<<~RUBY)
enum status: [OLD, ACTIVE]
^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead.
RUBY

expect_correction(<<~RUBY)
enum status: {OLD => 0, ACTIVE => 1}
RUBY
end

it 'autocorrects nested constants' do
expect_offense(<<~RUBY)
enum status: [STATUS::OLD, STATUS::ACTIVE]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead.
RUBY

expect_correction(<<~RUBY)
enum status: {STATUS::OLD => 0, STATUS::ACTIVE => 1}
RUBY
end
end
Expand Down