diff --git a/lib/rubocop/cop/rails/enum_hash.rb b/lib/rubocop/cop/rails/enum_hash.rb index cff550baf6..dd1257010f 100644 --- a/lib/rubocop/cop/rails/enum_hash.rb +++ b/lib/rubocop/cop/rails/enum_hash.rb @@ -30,6 +30,35 @@ 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 = "'#{value}'" if value.match(/\s/) + "#{value}: #{index}" + else + "#{child.source} => #{index}" + end + end end end end 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 a803c85a85..f6c249a65c 100644 --- a/spec/rubocop/cop/rails/enum_hash_spec.rb +++ b/spec/rubocop/cop/rails/enum_hash_spec.rb @@ -50,6 +50,12 @@ RUBY end end + + it 'autocorrects' do + expect( + autocorrect_source('enum status: [:active, :"very active", "completely archived", 42]') + ).to eq("enum status: { active: 0, 'very active': 1, 'completely archived' => 2, 42 => 3 }") + end end context 'when hash syntax is used' do