diff --git a/lib/rubocop/cop/rails/hash_enum.rb b/lib/rubocop/cop/rails/hash_enum.rb index b208851d5e..5f9a2a4e38 100644 --- a/lib/rubocop/cop/rails/hash_enum.rb +++ b/lib/rubocop/cop/rails/hash_enum.rb @@ -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 diff --git a/manual/cops_rails.md b/manual/cops_rails.md index 69253324c8..ba8739240e 100644 --- a/manual/cops_rails.md +++ b/manual/cops_rails.md @@ -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 diff --git a/spec/rubocop/cop/rails/hash_enum_spec.rb b/spec/rubocop/cop/rails/hash_enum_spec.rb index 9398d764d5..43c851f76b 100644 --- a/spec/rubocop/cop/rails/hash_enum_spec.rb +++ b/spec/rubocop/cop/rails/hash_enum_spec.rb @@ -57,4 +57,10 @@ expect_no_offenses('enum status: { active: 0, archived: 1 }') end end + + it 'autocorrects a enum with array syntax' do + expect( + autocorrect_source('enum status: [:active, "completely archived", 42]') + ).to eq("enum status: { active: 0, 'completely archived' => 1, 42 => 2 }") + end end