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

[#78] Autocorrect EnumHash Cop #95

Merged
merged 2 commits into from
Jul 29, 2019
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
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