Skip to content

Commit 9d54e36

Browse files
committed
[Fix #78] Improvements
1 parent e437bc6 commit 9d54e36

File tree

2 files changed

+18
-36
lines changed

2 files changed

+18
-36
lines changed

lib/rubocop/cop/rails/enum_hash.rb

Lines changed: 10 additions & 29 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)
@@ -50,35 +60,6 @@ def enum_name(key)
5060
key.source
5161
end
5262
end
53-
54-
def autocorrect(node)
55-
enum_values = node.children[2].children.first.children[1]
56-
to_replace = enum_values.loc.expression
57-
values_hash = "{ #{converted_values(enum_values)} }"
58-
59-
->(corrector) { corrector.replace(to_replace, values_hash) }
60-
end
61-
62-
private
63-
64-
def converted_values(enum_values)
65-
enum_values.children.each_with_index.map do |child, index|
66-
hash_entry_as_string(child, index)
67-
end.join(', ')
68-
end
69-
70-
def hash_entry_as_string(child, index)
71-
value = child.children.first
72-
case value
73-
when String
74-
"'#{value}' => #{index}"
75-
when Symbol
76-
value = "'#{value}'" if value =~ /\s/
77-
"#{value}: #{index}"
78-
else
79-
"#{child.source} => #{index}"
80-
end
81-
end
8263
end
8364
end
8465
end

spec/rubocop/cop/rails/enum_hash_spec.rb

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -81,13 +81,14 @@
8181
end
8282

8383
it 'autocorrects' do
84-
expect(
85-
autocorrect_source(
86-
'enum status: [:old, :"very active", "is archived", 42]'
87-
)
88-
).to eq(
89-
"enum status: { old: 0, 'very active': 1, 'is archived' => 2, 42 => 3 }"
90-
)
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
9192
end
9293
end
9394

0 commit comments

Comments
 (0)