Skip to content

Commit c64e808

Browse files
committed
[Fix: #1119] Fix an incorrect autocorrect for Rails/RedundantActiveRecordAllMethod when all has parentheses
1 parent a3711eb commit c64e808

File tree

3 files changed

+34
-1
lines changed

3 files changed

+34
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1119](https://github.com/rubocop/rubocop-rails/issues/1119): Fix an incorrect autocorrect for `Rails/RedundantActiveRecordAllMethod` when `all` has parentheses. ([@masato-bkn][])

lib/rubocop/cop/rails/redundant_active_record_all_method.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ module Rails
2222
# user.articles.order(:created_at)
2323
class RedundantActiveRecordAllMethod < Base
2424
include ActiveRecordHelper
25+
include RangeHelp
2526
extend AutoCorrector
2627

2728
MSG = 'Redundant `all` detected.'
@@ -134,12 +135,18 @@ def on_send(node)
134135
return unless followed_by_query_method?(node.parent)
135136
return if node.receiver.nil? && !inherit_active_record_base?(node)
136137

137-
range_of_all_method = node.loc.selector
138+
range_of_all_method = offense_range(node)
138139
add_offense(range_of_all_method) do |collector|
139140
collector.remove(range_of_all_method)
140141
collector.remove(node.parent.loc.dot)
141142
end
142143
end
144+
145+
private
146+
147+
def offense_range(node)
148+
range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
149+
end
143150
end
144151
end
145152
end

spec/rubocop/cop/rails/redundant_active_record_all_method_spec.rb

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -280,6 +280,31 @@
280280
RUBY
281281
end
282282
end
283+
284+
context 'when `all` has parentheses' do
285+
it 'does not register an offense when no method follows `all`' do
286+
expect_no_offenses(<<~RUBY)
287+
User.all()
288+
RUBY
289+
end
290+
291+
it 'registers an offense and corrects when method in `ActiveRecord::Querying::QUERYING_METHODS` follows `all`' do
292+
expect_offense(<<~RUBY)
293+
User.all().order(:created_at)
294+
^^^^^ Redundant `all` detected.
295+
RUBY
296+
297+
expect_correction(<<~RUBY)
298+
User.order(:created_at)
299+
RUBY
300+
end
301+
302+
it 'does not register an offense when method not in `ActiveRecord::Querying::QUERYING_METHODS` follows `all`' do
303+
expect_no_offenses(<<~RUBY)
304+
User.all().do_something
305+
RUBY
306+
end
307+
end
283308
end
284309

285310
context 'with no receiver' do

0 commit comments

Comments
 (0)