/
where_missing.rb
75 lines (61 loc) · 2.29 KB
/
where_missing.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
64
65
66
67
68
69
70
71
72
73
74
75
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Check for the use `left_joins` and `where` method for finding missing relationship records.
#
# This cop is enabled in Rails 6.1 or higher.
#
# @example
# # bad
# Foo.left_joins(:foo).where(foos: { id: nil })
#
# # good
# Foo.where.missing(:foo)
#
class WhereMissing < Base
include RangeHelp
extend AutoCorrector
extend TargetRailsVersion
MSG = 'Use `where.missing` instead.'
RESTRICT_ON_SEND = %i[where].freeze
minimum_target_rails_version 6.1
# @!method find_missing_relationship_record?(node)
def_node_search :find_missing_relationship_record?, <<~PATTERN
(send (send ... :left_joins (sym _)) :where (hash (pair (sym _) (hash (pair (sym :id) (nil))))))
PATTERN
# @!method left_joins_argument(node)
def_node_matcher :left_joins_argument, <<~PATTERN
(send (const nil? _) :left_joins (sym $_))
PATTERN
# @!method where_argument(node)
def_node_matcher :where_argument, <<~PATTERN
(send ... (hash (pair (sym $_) _)))
PATTERN
def on_send(node)
return unless find_missing_relationship_record?(node)
left_joins_node = node.receiver
return unless same_relationship?(node, left_joins_node)
register_offense(node, left_joins_node)
end
private
def register_offense(node, left_joins_node)
range = range_between(left_joins_node.loc.selector.begin_pos, left_joins_node.parent.loc.end.end_pos)
add_offense(range) do |corrector|
autocorrect(node, left_joins_node, corrector)
end
end
def autocorrect(node, left_joins_node, corrector)
corrector.replace(range_between(left_joins_node.loc.selector.begin_pos, node.loc.end.end_pos),
replaced_method(left_joins_node))
end
def same_relationship?(where_node, left_joins_node)
"#{left_joins_argument(left_joins_node)}s" == where_argument(where_node).to_s
end
def replaced_method(node)
"where.missing(:#{left_joins_argument(node)})"
end
end
end
end
end