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

Support Rails 7 syntax for Rails/EnumHash cop #1309

Merged
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
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1309](https://github.com/rubocop/rubocop-rails/pull/1309): Support Rails 7 syntax for `Rails/EnumHash` cop. ([@ytjmt][])
39 changes: 31 additions & 8 deletions lib/rubocop/cop/rails/enum_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ module Rails
#
# @example
# # bad
# enum :status, [:active, :archived]
#
# # good
# enum :status, { active: 0, archived: 1 }
#
# # bad
# enum status: [:active, :archived]
#
# # good
Expand All @@ -23,7 +29,11 @@ class EnumHash < Base
MSG = 'Enum defined as an array found in `%<enum>s` enum declaration. Use hash syntax instead.'
RESTRICT_ON_SEND = %i[enum].freeze

def_node_matcher :enum?, <<~PATTERN
def_node_matcher :enum_with_array?, <<~PATTERN
(send nil? :enum $_ ${array} ...)
PATTERN

def_node_matcher :enum_with_old_syntax?, <<~PATTERN
(send nil? :enum (hash $...))
PATTERN

Expand All @@ -32,24 +42,30 @@ class EnumHash < Base
PATTERN

def on_send(node)
enum?(node) do |pairs|
target_rails_version >= 7.0 && enum_with_array?(node) do |key, array|
add_offense(array, message: message(key)) do |corrector|
corrector.replace(array, build_hash(array))
end
end

enum_with_old_syntax?(node) do |pairs|
pairs.each do |pair|
key, array = array_pair?(pair)
next unless key

add_offense(array, message: format(MSG, enum: enum_name(key))) do |corrector|
hash = array.children.each_with_index.map do |elem, index|
"#{source(elem)} => #{index}"
end.join(', ')

corrector.replace(array, "{#{hash}}")
add_offense(array, message: message(key)) do |corrector|
corrector.replace(array, build_hash(array))
end
end
end
end

private

def message(key)
format(MSG, enum: enum_name(key))
end

def enum_name(key)
case key.type
when :sym, :str
Expand All @@ -69,6 +85,13 @@ def source(elem)
elem.source
end
end

def build_hash(array)
hash = array.children.each_with_index.map do |elem, index|
"#{source(elem)} => #{index}"
end.join(', ')
"{#{hash}}"
end
end
end
end
Expand Down
Loading