Skip to content

Commit

Permalink
Fix a false positive for RedundantActiveRecordAllMethod
Browse files Browse the repository at this point in the history
Resolves #1114 (comment)

This PR fixes a false positive for `RedundantActiveRecordAllMethod`
when using `find` with block argument.

`Enumerable#find` and `ActiveRecord::Base#find` have different arguments,
So false positives can be prevented.
  • Loading branch information
koic committed Sep 19, 2023
1 parent 68a0d3d commit 60ccbef
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1126](https://github.com/rubocop/rubocop-rails/pull/1126): Fix a false positive for `RedundantActiveRecordAllMethod` when using `find` with block argument. ([@koic][])
8 changes: 8 additions & 0 deletions lib/rubocop/cop/rails/redundant_active_record_all_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ class RedundantActiveRecordAllMethod < Base
def on_send(node)
return unless followed_by_query_method?(node.parent)
return if node.receiver.nil? && !inherit_active_record_base?(node)
return if use_find_method_with_block?(node)

range_of_all_method = offense_range(node)
add_offense(range_of_all_method) do |collector|
Expand All @@ -144,6 +145,13 @@ def on_send(node)

private

def use_find_method_with_block?(node)
parent = node.parent
return false unless parent.method?(:find)

parent.parent&.block_type? || parent.parent&.numblock_type? || parent.first_argument&.block_pass_type?
end

def offense_range(node)
range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
end
Expand Down
18 changes: 18 additions & 0 deletions spec/rubocop/cop/rails/redundant_active_record_all_method_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -387,5 +387,23 @@ class User < ::ActiveRecord::Base
end
RUBY
end

it 'does not register an offense when using `find` with block' do
expect_no_offenses(<<~RUBY)
User.all.find { |item| item.do_something }
RUBY
end

it 'does not register an offense when using `find` with numbered block' do
expect_no_offenses(<<~RUBY)
User.all.find { _1.do_something }
RUBY
end

it 'does not register an offense when using `find` with symbol block' do
expect_no_offenses(<<~RUBY)
User.all.find(&:do_something)
RUBY
end
end
end

0 comments on commit 60ccbef

Please sign in to comment.