Skip to content

Commit

Permalink
Merge pull request #8741 from dvandersluis/fix-hash-as-last-array-imp…
Browse files Browse the repository at this point in the history
…licit

[Fix #8740] Fix a false positive for `Style/HashAsLastArrayItem` when the hash is in an implicit array
  • Loading branch information
koic committed Sep 17, 2020
2 parents c831f0e + 4308c4a commit f1ed705
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -8,6 +8,7 @@
* [#8710](https://github.com/rubocop-hq/rubocop/issues/8710): Fix a false positive for `Layout/RescueEnsureAlignment` when `Layout/BeginEndAlignment` cop is not enabled status. ([@koic][])
* [#8726](https://github.com/rubocop-hq/rubocop/issues/8726): Fix a false positive for `Naming/VariableNumber` when naming multibyte character variable name. ([@koic][])
* [#8730](https://github.com/rubocop-hq/rubocop/issues/8730): Fix an error for `Lint/UselessTimes` when there is a blank line in the method definition. ([@koic][])
* [#8740](https://github.com/rubocop-hq/rubocop/issues/8740): Fix a false positive for `Style/HashAsLastArrayItem` when the hash is in an implicit array. ([@dvandersluis][])

### Changes

Expand Down
21 changes: 15 additions & 6 deletions lib/rubocop/cop/style/hash_as_last_array_item.rb
Expand Up @@ -33,7 +33,8 @@ class HashAsLastArrayItem < Base
extend AutoCorrector

def on_hash(node)
return unless last_array_item?(node)
return unless (array = containing_array(node))
return unless last_array_item?(array, node) && explicit_array?(array)

if braces_style?
check_braces(node)
Expand All @@ -44,12 +45,20 @@ def on_hash(node)

private

def last_array_item?(node)
parent = node.parent
return false unless parent&.array_type?
return false if parent.child_nodes.all?(&:hash_type?)
def containing_array(hash_node)
parent = hash_node.parent
parent if parent&.array_type?
end

def last_array_item?(array, node)
return false if array.child_nodes.all?(&:hash_type?)

array.children.last.equal?(node)
end

parent.children.last.equal?(node)
def explicit_array?(array)
# an implicit array cannot have an "unbraced" hash
array.square_brackets?
end

def check_braces(node)
Expand Down
6 changes: 6 additions & 0 deletions spec/rubocop/cop/style/hash_as_last_array_item_spec.rb
Expand Up @@ -83,5 +83,11 @@
[1, {}]
RUBY
end

it 'does not register an offense when passing an implicit array to a setter' do
expect_no_offenses(<<~RUBY)
cache_store = :redis_cache_store, { url: ENV['REDIS_URL'] }
RUBY
end
end
end

0 comments on commit f1ed705

Please sign in to comment.