Skip to content

Commit

Permalink
[Fix rubocop#78] Autocorrect HashEnum Cop
Browse files Browse the repository at this point in the history
  • Loading branch information
santib committed Jul 24, 2019
1 parent 8808dab commit 69cb551
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 1 deletion.
28 changes: 28 additions & 0 deletions lib/rubocop/cop/rails/hash_enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,34 @@ def on_send(node)
add_offense(node, message: format(MSG, enum: name))
end
end

def autocorrect(node)
enum_values = node.children[2].children.first.children[1]
to_replace = enum_values.loc.expression
values_hash = "{ #{converted_values(enum_values)} }"

->(corrector) { corrector.replace(to_replace, values_hash) }
end

private

def converted_values(enum_values)
enum_values.children.each_with_index.map do |child, index|
hash_entry_as_string(child, index)
end.join(', ')
end

def hash_entry_as_string(child, index)
value = child.children.first
case value
when String
"'#{value}' => #{index}"
when Symbol
"#{value}: #{index}"
else
"#{child.source} => #{index}"
end
end
end
end
end
Expand Down
2 changes: 1 addition & 1 deletion manual/cops_rails.md
Original file line number Diff line number Diff line change
Expand Up @@ -900,7 +900,7 @@ Include | `app/models/**/*.rb` | Array

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

This cop looks for enums written with array syntax

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

it 'autocorrects' do
expect(
autocorrect_source('enum status: [:active, "completely archived", 42]')
).to eq("enum status: { active: 0, 'completely archived' => 1, 42 => 2 }")
end
end

context 'when hash syntax is used' do
Expand Down

0 comments on commit 69cb551

Please sign in to comment.