Skip to content

Commit

Permalink
Fix an incorrect autocorrect for Rails/EnumHash
Browse files Browse the repository at this point in the history
Closes rubocop#114.

This PR fixes an incorrect autocorrect for `Rails/EnumHash`
when using nested constants.
  • Loading branch information
koic committed Oct 21, 2019
1 parent 6bb2e9f commit e877a13
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 7 deletions.
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

0 comments on commit e877a13

Please sign in to comment.