Skip to content

Commit

Permalink
[Fix rubocop#504] Rails/FindBy being wrongly triggered on non Active …
Browse files Browse the repository at this point in the history
…Record methods
  • Loading branch information
nvasilevski committed Jun 21, 2021
1 parent 6986c02 commit d2a6ae3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/rubocop/cop/rails/find_by.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,12 @@ class FindBy < Base
MSG = 'Use `find_by` instead of `where.%<method>s`.'
RESTRICT_ON_SEND = %i[first take].freeze

def_node_matcher :preceding_where?, <<~PATTERN
(send ({send csend} _ :where ...) {:first :take})
PATTERN

def on_send(node)
return unless preceding_where?(node)
return if ignore_where_first? && node.method?(:first)

range = range_between(node.receiver.loc.selector.begin_pos, node.loc.selector.end_pos)
Expand Down
20 changes: 20 additions & 0 deletions spec/rubocop/cop/rails/find_by_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,24 @@
expect_no_corrections
end
end

context 'when receiver is not an Active Record' do
context 'when method is Array#take' do
it 'does not register an offence' do
expect_no_offenses(<<~RUBY)
array = Array.new(1) { rand }
array.compact.take
RUBY
end
end

context 'when method is Array#first' do
it 'does not register an offence' do
expect_no_offenses(<<~RUBY)
array = Array.new(1) { rand }
array.compact.first
RUBY
end
end
end
end

0 comments on commit d2a6ae3

Please sign in to comment.