Skip to content

Commit

Permalink
[Fix rubocop#1343] False negatives for `Rails/EnumSyntax´
Browse files Browse the repository at this point in the history
I don't believe there is any issue with just looking at all value types.
It just translates `foo: bar` into `:foo, bar`.
  • Loading branch information
Earlopain committed Sep 1, 2024
1 parent 5c8b114 commit 99eb09b
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 14 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_negatives_enum_syntax.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1343](https://github.com/rubocop/rubocop-rails/issues/1343): Fix false negatives for `Rails/EnumSyntax` for non-literal mappings. ([@earlopain][])
21 changes: 7 additions & 14 deletions lib/rubocop/cop/rails/enum_syntax.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,6 @@ class EnumSyntax < Base
(send nil? :enum $_ ${array hash} $_)
PATTERN

def_node_matcher :enum_values, <<~PATTERN
(pair $_ ${array hash})
PATTERN

def_node_matcher :enum_options, <<~PATTERN
(pair $_ $_)
PATTERN

def on_send(node)
check_and_correct_keyword_args(node)
check_enum_options(node)
Expand All @@ -52,20 +44,17 @@ def on_send(node)
def check_and_correct_keyword_args(node)
enum?(node) do |pairs|
pairs.each do |pair|
key, values = enum_values(pair)
next unless key
next if option_key?(pair)

correct_keyword_args(node, key, values, pairs[1..])
correct_keyword_args(node, pair.key, pair.value, pairs[1..])
end
end
end

def check_enum_options(node)
enum_with_options?(node) do |key, _, options|
options.children.each do |option|
name, = enum_options(option)

add_offense(name, message: format(MSG_OPTIONS, enum: enum_name_value(key))) if name.source[0] == '_'
add_offense(option.key, message: format(MSG_OPTIONS, enum: enum_name_value(key))) if option_key?(option)
end
end
end
Expand Down Expand Up @@ -107,6 +96,10 @@ def enum_name(elem)
end
end

def option_key?(pair)
pair.key.source[0] == '_'
end

def correct_options(options)
corrected_options = options.map do |pair|
name = if pair.key.source[0] == '_'
Expand Down
13 changes: 13 additions & 0 deletions spec/rubocop/cop/rails/enum_syntax_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,19 @@
end
end

context 'when the enum value is not a literal' do
it 'registers an offense' do
expect_offense(<<~RUBY)
enum key: %i[foo bar].map.with_index { |v, i| [v, i] }.to_h
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Enum defined with keyword arguments in `key` enum declaration. Use positional arguments instead.
RUBY

expect_correction(<<~RUBY)
enum :key, %i[foo bar].map.with_index { |v, i| [v, i] }.to_h
RUBY
end
end

it 'autocorrects' do
expect_offense(<<~RUBY)
enum status: { active: 0, archived: 1 }
Expand Down

0 comments on commit 99eb09b

Please sign in to comment.