Skip to content

Commit

Permalink
Support Rails 7 syntax for Rails/EnumHash cop
Browse files Browse the repository at this point in the history
  • Loading branch information
ytjmt committed Jul 13, 2024
1 parent 3e91c03 commit 78c6796
Show file tree
Hide file tree
Showing 3 changed files with 354 additions and 117 deletions.
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

0 comments on commit 78c6796

Please sign in to comment.