Skip to content

Commit aedb97c

Browse files
authored
Merge pull request #95 from santib/autocorrect-hashenum-cop
[#78] Autocorrect EnumHash Cop
2 parents 51c57d8 + 9d54e36 commit aedb97c

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

lib/rubocop/cop/rails/enum_hash.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,16 @@ def on_send(node)
4040
end
4141
end
4242

43+
def autocorrect(node)
44+
range = node.loc.expression
45+
hash = node
46+
.children
47+
.each_with_index
48+
.map { |elem, index| [elem.children.first, index] }.to_h
49+
50+
->(corrector) { corrector.replace(range, hash.to_s) }
51+
end
52+
4353
private
4454

4555
def enum_name(key)

manual/cops_rails.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -646,7 +646,7 @@ Whitelist | `find_by_sql` | Array
646646

647647
Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged
648648
--- | --- | --- | --- | ---
649-
Enabled | Yes | No | 2.3 | -
649+
Enabled | Yes | Yes | 2.3 | -
650650

651651
This cop looks for enums written with array syntax.
652652

spec/rubocop/cop/rails/enum_hash_spec.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,17 @@
7979
RUBY
8080
end
8181
end
82+
83+
it 'autocorrects' do
84+
expect_offense(<<~RUBY)
85+
enum status: [:old, :"very active", "is archived", 42]
86+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead.
87+
RUBY
88+
89+
expect_correction(<<~RUBY)
90+
enum status: {:old=>0, :"very active"=>1, "is archived"=>2, 42=>3}
91+
RUBY
92+
end
8293
end
8394

8495
context 'when hash syntax is used' do

0 commit comments

Comments
 (0)