forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_by.rb
55 lines (46 loc) · 1.62 KB
/
find_by.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop is used to identify usages of `where.first` and
# change them to use `find_by` instead.
#
# @example
# # bad
# User.where(name: 'Bruce').first
# User.where(name: 'Bruce').take
#
# # good
# User.find_by(name: 'Bruce')
class FindBy < Cop
include RangeHelp
MSG = 'Use `find_by` instead of `where.%<method>s`.'
TARGET_SELECTORS = %i[first take].freeze
def_node_matcher :where_first?, <<-PATTERN
(send ({send csend} _ :where ...) {:first :take})
PATTERN
def on_send(node)
return unless where_first?(node)
range = range_between(node.receiver.loc.selector.begin_pos,
node.loc.selector.end_pos)
add_offense(node, location: range,
message: format(MSG, method: node.method_name))
end
alias on_csend on_send
def autocorrect(node)
# Don't autocorrect where(...).first, because it can return different
# results from find_by. (They order records differently, so the
# 'first' record can be different.)
return if node.method?(:first)
where_loc = node.receiver.loc.selector
first_loc = range_between(node.loc.dot.begin_pos,
node.loc.selector.end_pos)
lambda do |corrector|
corrector.replace(where_loc, 'find_by')
corrector.replace(first_loc, '')
end
end
end
end
end
end