From e877a138db8d8fb207e8e1c6a53ad26cf9080e83 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Mon, 21 Oct 2019 13:03:05 +0900 Subject: [PATCH] Fix an incorrect autocorrect for `Rails/EnumHash` Closes #114. This PR fixes an incorrect autocorrect for `Rails/EnumHash` when using nested constants. --- CHANGELOG.md | 1 + lib/rubocop/cop/rails/enum_hash.rb | 10 ++++------ spec/rubocop/cop/rails/enum_hash_spec.rb | 24 +++++++++++++++++++++++- 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2fa62bc765..9ecb6037ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ * [#120](https://github.com/rubocop-hq/rubocop-rails/issues/120): Fix message for `Rails/SaveBang` when the save is in the body of a conditional. ([@jas14][]) * [#131](https://github.com/rubocop-hq/rubocop-rails/pull/131): Fix an incorrect autocorrect for `Rails/Presence` when using `[]` method. ([@forresty][]) +* [#142](https://github.com/rubocop-hq/rubocop-rails/pull/142): Fix an incorrect autocorrect for `Rails/EnumHash` when using nested constants. ([@koic][]) ## 2.3.2 (2019-09-01) diff --git a/lib/rubocop/cop/rails/enum_hash.rb b/lib/rubocop/cop/rails/enum_hash.rb index c1c39e1a66..cba3365190 100644 --- a/lib/rubocop/cop/rails/enum_hash.rb +++ b/lib/rubocop/cop/rails/enum_hash.rb @@ -41,13 +41,11 @@ def on_send(node) end def autocorrect(node) - range = node.loc.expression - hash = node - .children - .each_with_index - .map { |elem, index| [elem.children.first, index] }.to_h + hash = node.children.each_with_index.map do |elem, index| + "#{elem.source} => #{index}" + end.join(', ') - ->(corrector) { corrector.replace(range, hash.to_s) } + ->(corrector) { corrector.replace(node.loc.expression, "{#{hash}}") } end private diff --git a/spec/rubocop/cop/rails/enum_hash_spec.rb b/spec/rubocop/cop/rails/enum_hash_spec.rb index 43016f853c..0f216384fd 100644 --- a/spec/rubocop/cop/rails/enum_hash_spec.rb +++ b/spec/rubocop/cop/rails/enum_hash_spec.rb @@ -87,7 +87,29 @@ RUBY expect_correction(<<~RUBY) - enum status: {:old=>0, :"very active"=>1, "is archived"=>2, 42=>3} + enum status: {:old => 0, :"very active" => 1, "is archived" => 2, 42 => 3} + RUBY + end + + it 'autocorrects constants' do + expect_offense(<<~RUBY) + enum status: [OLD, ACTIVE] + ^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead. + RUBY + + expect_correction(<<~RUBY) + enum status: {OLD => 0, ACTIVE => 1} + RUBY + end + + it 'autocorrects nested constants' do + expect_offense(<<~RUBY) + enum status: [STATUS::OLD, STATUS::ACTIVE] + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Enum defined as an array found in `status` enum declaration. Use hash syntax instead. + RUBY + + expect_correction(<<~RUBY) + enum status: {STATUS::OLD => 0, STATUS::ACTIVE => 1} RUBY end end