diff --git a/changelog/fix_false_positive_for_rails_redundant_active_record_dll_method.md b/changelog/fix_false_positive_for_rails_redundant_active_record_dll_method.md new file mode 100644 index 0000000000..1a4d0c0cee --- /dev/null +++ b/changelog/fix_false_positive_for_rails_redundant_active_record_dll_method.md @@ -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][]) diff --git a/config/default.yml b/config/default.yml index 8071f9e03b..bd61a764b2 100644 --- a/config/default.yml +++ b/config/default.yml @@ -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: diff --git a/lib/rubocop/cop/rails/redundant_active_record_all_method.rb b/lib/rubocop/cop/rails/redundant_active_record_all_method.rb index 9349179de3..0d206ad9b3 100644 --- a/lib/rubocop/cop/rails/redundant_active_record_all_method.rb +++ b/lib/rubocop/cop/rails/redundant_active_record_all_method.rb @@ -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 @@ -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| diff --git a/spec/rubocop/cop/rails/redundant_active_record_all_method_spec.rb b/spec/rubocop/cop/rails/redundant_active_record_all_method_spec.rb index 888f734b69..804ce4fed2 100644 --- a/spec/rubocop/cop/rails/redundant_active_record_all_method_spec.rb +++ b/spec/rubocop/cop/rails/redundant_active_record_all_method_spec.rb @@ -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