diff --git a/lib/rubocop/cop/rails/enum_hash.rb b/lib/rubocop/cop/rails/enum_hash.rb index 639b96f887..c1c39e1a66 100644 --- a/lib/rubocop/cop/rails/enum_hash.rb +++ b/lib/rubocop/cop/rails/enum_hash.rb @@ -40,6 +40,16 @@ def on_send(node) end end + def autocorrect(node) + range = node.loc.expression + hash = node + .children + .each_with_index + .map { |elem, index| [elem.children.first, index] }.to_h + + ->(corrector) { corrector.replace(range, hash.to_s) } + end + private def enum_name(key) diff --git a/manual/cops_rails.md b/manual/cops_rails.md index 2b12dae89e..017184d3c2 100644 --- a/manual/cops_rails.md +++ b/manual/cops_rails.md @@ -646,7 +646,7 @@ Whitelist | `find_by_sql` | Array Enabled by default | Safe | Supports autocorrection | VersionAdded | VersionChanged --- | --- | --- | --- | --- -Enabled | Yes | No | 2.3 | - +Enabled | Yes | Yes | 2.3 | - This cop looks for enums written with array syntax. diff --git a/spec/rubocop/cop/rails/enum_hash_spec.rb b/spec/rubocop/cop/rails/enum_hash_spec.rb index cd1201ca64..43016f853c 100644 --- a/spec/rubocop/cop/rails/enum_hash_spec.rb +++ b/spec/rubocop/cop/rails/enum_hash_spec.rb @@ -79,6 +79,17 @@ RUBY end end + + it 'autocorrects' do + expect_offense(<<~RUBY) + enum status: [:old, :"very active", "is archived", 42] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead. + RUBY + + expect_correction(<<~RUBY) + enum status: {:old=>0, :"very active"=>1, "is archived"=>2, 42=>3} + RUBY + end end context 'when hash syntax is used' do