forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
duplicate_scope.rb
46 lines (40 loc) · 1.29 KB
/
duplicate_scope.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
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Checks for multiple scopes in a model that have the same `where` clause. This
# often means you copy/pasted a scope, updated the name, and forgot to change the condition.
#
# @example
#
# # bad
# scope :visible, -> { where(visible: true) }
# scope :hidden, -> { where(visible: true) }
#
# # good
# scope :visible, -> { where(visible: true) }
# scope :hidden, -> { where(visible: false) }
#
class DuplicateScope < Base
include ClassSendNodeHelper
MSG = 'Multiple scopes share this same where clause.'
def_node_matcher :scope, <<~PATTERN
(send nil? :scope _ $...)
PATTERN
def on_class(class_node)
offenses(class_node).each do |node|
add_offense(node)
end
end
private
def offenses(class_node)
class_send_nodes(class_node).select { |node| scope(node) }
.group_by { |node| scope(node) }
.select { |_, nodes| nodes.length > 1 }
.values
.flatten
end
end
end
end
end