forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pluck_id.rb
59 lines (51 loc) · 1.41 KB
/
pluck_id.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
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop enforces the use of `ids` over `pluck(:id)` and `pluck(primary_key)`.
#
# @safety
# This cop is unsafe if the receiver object is not an Active Record object.
#
# @example
# # bad
# User.pluck(:id)
# user.posts.pluck(:id)
#
# def self.user_ids
# pluck(primary_key)
# end
#
# # good
# User.ids
# user.posts.ids
#
# def self.user_ids
# ids
# end
#
class PluckId < Base
include RangeHelp
include ActiveRecordHelper
extend AutoCorrector
MSG = 'Use `ids` instead of `%<bad_method>s`.'
RESTRICT_ON_SEND = %i[pluck].freeze
def_node_matcher :pluck_id_call?, <<~PATTERN
(send _ :pluck {(sym :id) (send nil? :primary_key)})
PATTERN
def on_send(node)
return if !pluck_id_call?(node) || in_where?(node)
range = offense_range(node)
message = format(MSG, bad_method: range.source)
add_offense(range, message: message) do |corrector|
corrector.replace(offense_range(node), 'ids')
end
end
private
def offense_range(node)
range_between(node.loc.selector.begin_pos, node.loc.expression.end_pos)
end
end
end
end
end