From 717973b2a0f437b0dd626365cf7d32a539800b1c Mon Sep 17 00:00:00 2001 From: fatkodima Date: Tue, 14 Jul 2020 03:24:41 +0300 Subject: [PATCH] Fix a false positive for `Style/HashAsLastArrayItem` when hash is not a last array item --- CHANGELOG.md | 1 + lib/rubocop/cop/style/hash_as_last_array_item.rb | 9 ++++++++- spec/rubocop/cop/style/hash_as_last_array_item_spec.rb | 6 +++--- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fb880c433a6..57d8ff82670 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Bug fixes * [#8324](https://github.com/rubocop-hq/rubocop/issues/8324): Fix crash for `Layout/SpaceAroundMethodCallOperator` when using `Proc#call` shorthand syntax. ([@fatkodima][]) +* [#8323](https://github.com/rubocop-hq/rubocop/issues/8323): Fix a false positive for `Style/HashAsLastArrayItem` when hash is not a last array item. ([@fatkodima][]) ## 0.88.0 (2020-07-13) 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 e14339729aa..fe739e2f0de 100644 --- a/lib/rubocop/cop/style/hash_as_last_array_item.rb +++ b/lib/rubocop/cop/style/hash_as_last_array_item.rb @@ -25,7 +25,7 @@ class HashAsLastArrayItem < Base extend AutoCorrector def on_hash(node) - return unless node.parent&.array_type? + return unless last_array_item?(node) if braces_style? check_braces(node) @@ -36,6 +36,13 @@ def on_hash(node) private + def last_array_item?(node) + parent = node.parent + return false unless parent + + parent.array_type? && parent.values.last == node + end + def check_braces(node) return if node.braces? 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 ddb329b4880..a65336920a0 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 @@ -39,12 +39,12 @@ it 'registers an offense and corrects when hash with braces' do expect_offense(<<~RUBY) - [1, 2, { one: 1, two: 2 }] - ^^^^^^^^^^^^^^^^^^ Omit the braces around the hash. + [{ one: 1 }, 2, { three: 3 }] + ^^^^^^^^^^^^ Omit the braces around the hash. RUBY expect_correction(<<~RUBY) - [1, 2, one: 1, two: 2 ] + [{ one: 1 }, 2, three: 3 ] RUBY end