diff --git a/CHANGELOG.md b/CHANGELOG.md index f2604dbf0d..3d7f88a6f4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#159](https://github.com/rubocop-hq/rubocop-rails/issues/159): Fix autocorrect for `Rails/EnumHash` when using % arrays notations. ([@ngouy][]) + ## 2.4.0 (2019-11-27) ### New features @@ -108,3 +112,4 @@ [@pocke]: https://github.com/pocke [@gyfis]: https:/github.com/gyfis [@DNA]: https://github.com/DNA +[@ngouy]: https://github.com/ngouy diff --git a/lib/rubocop/cop/rails/enum_hash.rb b/lib/rubocop/cop/rails/enum_hash.rb index cba3365190..fa36006d5e 100644 --- a/lib/rubocop/cop/rails/enum_hash.rb +++ b/lib/rubocop/cop/rails/enum_hash.rb @@ -42,7 +42,7 @@ def on_send(node) def autocorrect(node) hash = node.children.each_with_index.map do |elem, index| - "#{elem.source} => #{index}" + "#{source(elem)} => #{index}" end.join(', ') ->(corrector) { corrector.replace(node.loc.expression, "{#{hash}}") } @@ -58,6 +58,17 @@ def enum_name(key) key.source end end + + def source(elem) + case elem.type + when :str + elem.value.dump + when :sym + elem.value.inspect + else + elem.source + end + end end end end diff --git a/spec/rubocop/cop/rails/enum_hash_spec.rb b/spec/rubocop/cop/rails/enum_hash_spec.rb index 0f216384fd..2f6e86b4b5 100644 --- a/spec/rubocop/cop/rails/enum_hash_spec.rb +++ b/spec/rubocop/cop/rails/enum_hash_spec.rb @@ -112,6 +112,50 @@ enum status: {STATUS::OLD => 0, STATUS::ACTIVE => 1} RUBY end + + it 'autocorrects %w[] syntax' do + expect_offense(<<~RUBY) + enum status: %w[active archived] + ^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead. + RUBY + + expect_correction(<<~RUBY) + enum status: {"active" => 0, "archived" => 1} + RUBY + end + + it 'autocorrect %w() syntax' do + expect_offense(<<~RUBY) + enum status: %w(active archived) + ^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead. + RUBY + + expect_correction(<<~RUBY) + enum status: {"active" => 0, "archived" => 1} + RUBY + end + + it 'autocorrect %i[] syntax' do + expect_offense(<<~RUBY) + enum status: %i[active archived] + ^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead. + RUBY + + expect_correction(<<~RUBY) + enum status: {:active => 0, :archived => 1} + RUBY + end + + it 'autocorrect %i() syntax' do + expect_offense(<<~RUBY) + enum status: %i(active archived) + ^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead. + RUBY + + expect_correction(<<~RUBY) + enum status: {:active => 0, :archived => 1} + RUBY + end end context 'when hash syntax is used' do