diff --git a/lib/rubocop/cop/rails/find_by.rb b/lib/rubocop/cop/rails/find_by.rb index 14a4bdd1b3..726285296b 100644 --- a/lib/rubocop/cop/rails/find_by.rb +++ b/lib/rubocop/cop/rails/find_by.rb @@ -31,7 +31,12 @@ class FindBy < Base MSG = 'Use `find_by` instead of `where.%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) diff --git a/spec/rubocop/cop/rails/find_by_spec.rb b/spec/rubocop/cop/rails/find_by_spec.rb index fb80730cdd..cf865811f0 100644 --- a/spec/rubocop/cop/rails/find_by_spec.rb +++ b/spec/rubocop/cop/rails/find_by_spec.rb @@ -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