Skip to content

Commit

Permalink
Merge pull request #95 from santib/autocorrect-hashenum-cop
Browse files Browse the repository at this point in the history
[#78] Autocorrect EnumHash Cop
  • Loading branch information
koic authored Jul 29, 2019
2 parents 51c57d8 + 9d54e36 commit aedb97c
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
10 changes: 10 additions & 0 deletions lib/rubocop/cop/rails/enum_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ def on_send(node)
end
end

def autocorrect(node)
range = node.loc.expression
hash = node
.children
.each_with_index
.map { |elem, index| [elem.children.first, index] }.to_h

->(corrector) { corrector.replace(range, hash.to_s) }
end

private

def enum_name(key)
Expand Down
2 changes: 1 addition & 1 deletion manual/cops_rails.md
Original file line number Diff line number Diff line change
Expand Up @@ -646,7 +646,7 @@ Whitelist | `find_by_sql` | Array

Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged
--- | --- | --- | --- | ---
Enabled | Yes | No | 2.3 | -
Enabled | Yes | Yes | 2.3 | -

This cop looks for enums written with array syntax.

Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/enum_hash_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,17 @@
RUBY
end
end

it 'autocorrects' do
expect_offense(<<~RUBY)
enum status: [:old, :"very active", "is archived", 42]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead.
RUBY

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

context 'when hash syntax is used' do
Expand Down

0 comments on commit aedb97c

Please sign in to comment.