Skip to content

Commit

Permalink
Merge pull request #1127 from koic/fix_false_positive_for_rails_redun…
Browse files Browse the repository at this point in the history
…dant_active_record_dll_method

[Fix #1124] Fix false positives for `Rails/RedundantActiveRecordAllMethod`
  • Loading branch information
koic authored Sep 25, 2023
2 parents 7a0208b + 9923143 commit 0a57811
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1124](https://github.com/rubocop/rubocop-rails/issues/1124): Fix false positives for `Rails/RedundantActiveRecordAllMethod` when receiver is not an Active Record model. ([@koic][])
3 changes: 3 additions & 0 deletions config/default.yml
Original file line number Diff line number Diff line change
Expand Up @@ -801,6 +801,9 @@ Rails/RedundantActiveRecordAllMethod:
StyleGuide: 'https://rails.rubystyle.guide/#redundant-all'
Enabled: pending
Safe: false
AllowedReceivers:
- ActionMailer::Preview
- ActiveSupport::TimeZone
VersionAdded: '2.21'

Rails/RedundantAllowNil:
Expand Down
8 changes: 7 additions & 1 deletion lib/rubocop/cop/rails/redundant_active_record_all_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,14 @@ module Rails
# User.order(:created_at)
# users.where(id: ids)
# user.articles.order(:created_at)
#
# @example AllowedReceivers: ['ActionMailer::Preview', 'ActiveSupport::TimeZone'] (default)
# # good
# ActionMailer::Preview.all.first
# ActiveSupport::TimeZone.all.first
class RedundantActiveRecordAllMethod < Base
include ActiveRecordHelper
include AllowedReceivers
include RangeHelp
extend AutoCorrector

Expand Down Expand Up @@ -133,7 +139,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 node.receiver ? allowed_receiver?(node.receiver) : !inherit_active_record_base?(node)

range_of_all_method = offense_range(node)
add_offense(range_of_all_method) do |collector|
Expand Down
19 changes: 19 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 @@ -388,4 +388,23 @@ class User < ::ActiveRecord::Base
RUBY
end
end

context 'with `AllowedReceivers` config' do
let(:cop_config) do
{ 'AllowedReceivers' => %w[ActionMailer::Preview ActiveSupport::TimeZone] }
end

it 'registers an offense when not using allowed receiver' do
expect_offense(<<~RUBY)
User.all.first
^^^ Redundant `all` detected.
RUBY
end

it 'does not register an offense when using allowed receiver' do
expect_no_offenses(<<~RUBY)
ActiveSupport::TimeZone.all.first
RUBY
end
end
end

0 comments on commit 0a57811

Please sign in to comment.