Skip to content

Commit

Permalink
Merge pull request #353 from eugeneius/index_by_index_with_hash_reuse
Browse files Browse the repository at this point in the history
[Fix #338][Fix #350] Fix a false positive for Rails/IndexBy and Rails/IndexWith
  • Loading branch information
koic committed Sep 10, 2020
2 parents fa637ca + d8c62f5 commit de09957
Show file tree
Hide file tree
Showing 5 changed files with 19 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -6,6 +6,7 @@

* [#345](https://github.com/rubocop-hq/rubocop-rails/issues/345): Fix error of `Rails/AfterCommitOverride` on `after_commit` with a lambda. ([@pocke][])
* [#349](https://github.com/rubocop-hq/rubocop-rails/pull/349): Fix errors of `Rails/UniqueValidationWithoutIndex`. ([@Tietew][])
* [#338](https://github.com/rubocop-hq/rubocop-rails/issues/338): Fix a false positive for `Rails/IndexBy` and `Rails/IndexWith` when the `each_with_object` hash is used in the transformed key or value. ([@eugeneius][])

## 2.8.0 (2020-09-04)

Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rails/index_by.rb
Expand Up @@ -24,7 +24,7 @@ class IndexBy < Cop
(block
({send csend} _ :each_with_object (hash))
(args (arg $_el) (arg _memo))
({send csend} (lvar _memo) :[]= $_ (lvar _el)))
({send csend} (lvar _memo) :[]= $!`_memo (lvar _el)))
PATTERN

def_node_matcher :on_bad_to_h, <<~PATTERN
Expand Down
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rails/index_with.rb
Expand Up @@ -27,7 +27,7 @@ class IndexWith < Cop
(block
({send csend} _ :each_with_object (hash))
(args (arg $_el) (arg _memo))
({send csend} (lvar _memo) :[]= (lvar _el) $_))
({send csend} (lvar _memo) :[]= (lvar _el) $!`_memo))
PATTERN

def_node_matcher :on_bad_to_h, <<~PATTERN
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/rails/index_by_spec.rb
Expand Up @@ -68,6 +68,14 @@
end
end

context 'when the given hash is used in the key' do
it 'does not register an offense for `each_with_object`' do
expect_no_offenses(<<~RUBY)
x.each_with_object({}) { |el, h| h[h[el]] = el }
RUBY
end
end

context 'when `to_h` is given a block' do
it 'registers an offense for `map { ... }.to_h`' do
expect_offense(<<~RUBY)
Expand Down
8 changes: 8 additions & 0 deletions spec/rubocop/cop/rails/index_with_spec.rb
Expand Up @@ -69,6 +69,14 @@
end
end

context 'when the given hash is used in the value' do
it 'does not register an offense for `each_with_object`' do
expect_no_offenses(<<~RUBY)
x.each_with_object({}) { |el, h| h[el] = h.count }
RUBY
end
end

context 'when `to_h` is given a block' do
it 'registers an offense for `map { ... }.to_h`' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit de09957

Please sign in to comment.