forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_by.rb
63 lines (53 loc) · 1.81 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
56
57
58
59
60
61
62
63
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop is used to identify usages of `where.take` and change them to use `find_by` instead.
#
# And `where(...).first` can return different results from `find_by`.
# (They order records differently, so the "first" record can be different.)
#
# If you also want to detect `where.first`, you can set `IgnoreWhereFirst` to false.
#
# @example
# # bad
# User.where(name: 'Bruce').take
#
# # good
# User.find_by(name: 'Bruce')
#
# @example IgnoreWhereFirst: true (default)
# # good
# User.where(name: 'Bruce').first
#
# @example IgnoreWhereFirst: false
# # bad
# User.where(name: 'Bruce').first
class FindBy < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `find_by` instead of `where.%<method>s`.'
RESTRICT_ON_SEND = %i[first take].freeze
def on_send(node)
return if ignore_where_first? && node.method?(:first)
range = range_between(node.receiver.loc.selector.begin_pos, node.loc.selector.end_pos)
add_offense(range, message: format(MSG, method: node.method_name)) do |corrector|
autocorrect(corrector, node)
end
end
alias on_csend on_send
private
def autocorrect(corrector, node)
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)
corrector.replace(where_loc, 'find_by')
corrector.replace(first_loc, '')
end
def ignore_where_first?
cop_config.fetch('IgnoreWhereFirst', true)
end
end
end
end
end