Skip to content

Commit

Permalink
[Fix #512] Fix a false positive for Rails/FindBy
Browse files Browse the repository at this point in the history
Fix #512

This PR fixes a false positive for `Rails/FindBy`
when using `take` with arguments.
  • Loading branch information
koic committed Jul 1, 2021
1 parent 37de74e commit 6a5406a
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Bug fixes

* [#515](https://github.com/rubocop/rubocop-rails/issues/515): Fix an error for `Rails/BulkChangeTable` when using Psych 4.0. ([@koic][])
* [#512](https://github.com/rubocop/rubocop-rails/issues/512): Fix a false positive for `Rails/FindBy` when using `take` with arguments. ([@koic][])

## 2.11.1 (2021-06-25)

Expand Down
8 changes: 6 additions & 2 deletions lib/rubocop/cop/rails/find_by.rb
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,10 @@ class FindBy < Base
RESTRICT_ON_SEND = %i[first take].freeze

def on_send(node)
return unless where_method?(node.receiver)
return unless node.arguments.empty? && where_method?(node.receiver)
return if ignore_where_first? && node.method?(:first)

range = range_between(node.receiver.loc.selector.begin_pos, node.loc.selector.end_pos)
range = offense_range(node)

add_offense(range, message: format(MSG, method: node.method_name)) do |corrector|
autocorrect(corrector, node)
Expand All @@ -51,6 +51,10 @@ def where_method?(receiver)
receiver.respond_to?(:method?) && receiver.method?(:where)
end

def offense_range(node)
range_between(node.receiver.loc.selector.begin_pos, node.loc.selector.end_pos)
end

def autocorrect(corrector, node)
return if node.method?(:first)

Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/rails/find_by_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@
RUBY
end

it 'does not register an offense when using `take` with arguments' do
expect_no_offenses(<<~RUBY)
User.where(attr: arg).take(5)
RUBY
end

it 'does not register an offense when calling `take` after block' do
expect_no_offenses(<<~RUBY)
do_something {}.take(5)
Expand Down Expand Up @@ -72,6 +78,12 @@

expect_no_corrections
end

it 'does not register an offense when using `first` with arguments' do
expect_no_offenses(<<~RUBY)
User.where(attr: arg).first(5)
RUBY
end
end

context 'when receiver is not an Active Record' do
Expand Down

0 comments on commit 6a5406a

Please sign in to comment.