Skip to content

Commit fc9bf0c

Browse files
committed
[Fix: #1109] Fix error for Rails/RedundantActiveRecordAllMethod when all is an argument for AR methods
1 parent 3932c01 commit fc9bf0c

File tree

3 files changed

+34
-7
lines changed

3 files changed

+34
-7
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1109](https://github.com/rubocop/rubocop-rails/issues/1109): Fix error for `Rails/RedundantActiveRecordAllMethod` when `all` is an argument for AR methods.([@masato-bkn][])

lib/rubocop/cop/rails/redundant_active_record_all_method.rb

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -124,19 +124,20 @@ class RedundantActiveRecordAllMethod < Base
124124
update_all
125125
where
126126
without
127-
].freeze
127+
].to_set.freeze
128128

129-
def on_send(node)
130-
query_node = node.parent
129+
def_node_matcher :followed_by_query_method?, <<~PATTERN
130+
(send (send _ :all ...) QUERYING_METHODS ...)
131+
PATTERN
131132

132-
return unless query_node&.send_type?
133-
return unless QUERYING_METHODS.include?(query_node.method_name)
133+
def on_send(node)
134+
return unless followed_by_query_method?(node.parent)
134135
return if node.receiver.nil? && !inherit_active_record_base?(node)
135136

136137
range_of_all_method = node.loc.selector
137138
add_offense(range_of_all_method) do |collector|
138139
collector.remove(range_of_all_method)
139-
collector.remove(query_node.loc.dot)
140+
collector.remove(node.parent.loc.dot)
140141
end
141142
end
142143
end

spec/rubocop/cop/rails/redundant_active_record_all_method_spec.rb

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@
9999
update_all
100100
where
101101
without
102-
]
102+
].to_set
103103
)
104104
end
105105
end
@@ -235,6 +235,31 @@
235235
User.all.map(&:do_something)
236236
RUBY
237237
end
238+
239+
context 'when `all` is used as a method parameter' do
240+
it 'does not register an offense when no method follows `all`' do
241+
expect_no_offenses(<<~RUBY)
242+
do_something(User.all)
243+
RUBY
244+
end
245+
246+
it 'registers an offense and corrects when `ActiveRecord::Querying::QUERYING_METHODS` follows `all`' do
247+
expect_offense(<<~RUBY)
248+
do_something(User.all.order(:created_at))
249+
^^^ Redundant `all` detected.
250+
RUBY
251+
252+
expect_correction(<<~RUBY)
253+
do_something(User.order(:created_at))
254+
RUBY
255+
end
256+
257+
it 'does not register an offense when method matches `ActiveRecord::Querying::QUERYING_METHODS`' do
258+
expect_no_offenses(<<~RUBY)
259+
sum(User.all)
260+
RUBY
261+
end
262+
end
238263
end
239264

240265
context 'with no receiver' do

0 commit comments

Comments
 (0)