Skip to content

Commit

Permalink
Merge pull request #1120 from masato-bkn/fix_incorrect_autocorrect_fo…
Browse files Browse the repository at this point in the history
…r_rails_redundant_active_record_all_method_when_all_has_parentheses

[Fix: #1119] Fix an incorrect autocorrect for `Rails/RedundantActiveRecordAllMethod`  when `all` has parentheses
  • Loading branch information
koic committed Sep 18, 2023
2 parents 5b3dfb2 + c64e808 commit 85de912
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1119](https://github.com/rubocop/rubocop-rails/issues/1119): Fix an incorrect autocorrect for `Rails/RedundantActiveRecordAllMethod` when `all` has parentheses. ([@masato-bkn][])
9 changes: 8 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 @@ -22,6 +22,7 @@ module Rails
# user.articles.order(:created_at)
class RedundantActiveRecordAllMethod < Base
include ActiveRecordHelper
include RangeHelp
extend AutoCorrector

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

range_of_all_method = node.loc.selector
range_of_all_method = offense_range(node)
add_offense(range_of_all_method) do |collector|
collector.remove(range_of_all_method)
collector.remove(node.parent.loc.dot)
end
end

private

def offense_range(node)
range_between(node.loc.selector.begin_pos, node.source_range.end_pos)
end
end
end
end
Expand Down
25 changes: 25 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 @@ -280,6 +280,31 @@
RUBY
end
end

context 'when `all` has parentheses' do
it 'does not register an offense when no method follows `all`' do
expect_no_offenses(<<~RUBY)
User.all()
RUBY
end

it 'registers an offense and corrects when method in `ActiveRecord::Querying::QUERYING_METHODS` follows `all`' do
expect_offense(<<~RUBY)
User.all().order(:created_at)
^^^^^ Redundant `all` detected.
RUBY

expect_correction(<<~RUBY)
User.order(:created_at)
RUBY
end

it 'does not register an offense when method not in `ActiveRecord::Querying::QUERYING_METHODS` follows `all`' do
expect_no_offenses(<<~RUBY)
User.all().do_something
RUBY
end
end
end

context 'with no receiver' do
Expand Down

0 comments on commit 85de912

Please sign in to comment.