From 28778a6db6f9dbe599db6c65d128de382ed8519f Mon Sep 17 00:00:00 2001 From: Felipe Sateler Date: Wed, 9 Sep 2020 19:05:48 -0300 Subject: [PATCH] Fix an error for Style/HashAsLastArrayItem with no_braces for empty hash When `EnforcedStyle` is set to `no_braces`, rubocop was attempting to correct `[1, {}]` into `[1, ]`, which is not valid. An empty hash cannot omit the braces. --- CHANGELOG.md | 2 ++ lib/rubocop/cop/style/hash_as_last_array_item.rb | 1 + .../cop/style/hash_as_last_array_item_spec.rb | 12 ++++++++++++ 3 files changed, 15 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 04518ccb46c..eed0be5c590 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,7 @@ * [#8664](https://github.com/rubocop-hq/rubocop/issues/8664): Fix a false positive for `Naming/BinaryOperatorParameterName` when naming multibyte character method name. ([@koic][]) * [#8604](https://github.com/rubocop-hq/rubocop/issues/8604): Fix a false positive for `Bundler/DuplicatedGem` when gem is duplciated in condition. ([@tejasbubane][]) * [#8671](https://github.com/rubocop-hq/rubocop/issues/8671): Fix an error for `Style/ExplicitBlockArgument` when using safe navigation method call. ([@koic][]) +* [#8681](https://github.com/rubocop-hq/rubocop/pull/8681): Fix an error for `Style/HashAsLastArrayItem` with `no_braces` for empty hash. ([@fsateler][]) ### Changes @@ -4855,3 +4856,4 @@ [@jaimerave]: https://github.com/jaimerave [@Skipants]: https://github.com/Skipants [@sascha-wolf]: https://github.com/sascha-wolf +[@fsateler]: https://github.com/fsateler diff --git a/lib/rubocop/cop/style/hash_as_last_array_item.rb b/lib/rubocop/cop/style/hash_as_last_array_item.rb index 8e253ae4056..2f83581500b 100644 --- a/lib/rubocop/cop/style/hash_as_last_array_item.rb +++ b/lib/rubocop/cop/style/hash_as_last_array_item.rb @@ -62,6 +62,7 @@ def check_braces(node) def check_no_braces(node) return unless node.braces? + return if node.children.empty? # Empty hash cannot be "unbraced" add_offense(node, message: 'Omit the braces around the hash.') do |corrector| corrector.remove(node.loc.begin) diff --git a/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb b/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb index 16914a149f8..13949f64592 100644 --- a/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb +++ b/spec/rubocop/cop/style/hash_as_last_array_item_spec.rb @@ -36,6 +36,12 @@ [{ one: 1 }, { two: 2 }] RUBY end + + it 'does not register an offense when the hash is empty' do + expect_no_offenses(<<~RUBY) + [1, {}] + RUBY + end end context 'when EnforcedStyle is no_braces' do @@ -71,5 +77,11 @@ [{ one: 1 }, { two: 2 }] RUBY end + + it 'does not register an offense when the hash is empty' do + expect_no_offenses(<<~RUBY) + [1, {}] + RUBY + end end end