-
-
Notifications
You must be signed in to change notification settings - Fork 263
/
negate_include.rb
42 lines (37 loc) · 1.08 KB
/
negate_include.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
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Enforces the use of `collection.exclude?(obj)`
# over `!collection.include?(obj)`.
#
# @safety
# This cop is unsafe because false positive will occur for
# receiver objects that do not have an `exclude?` method. (e.g. `IPAddr`)
#
# @example
# # bad
# !array.include?(2)
# !hash.include?(:key)
#
# # good
# array.exclude?(2)
# hash.exclude?(:key)
#
class NegateInclude < Base
extend AutoCorrector
MSG = 'Use `.exclude?` and remove the negation part.'
RESTRICT_ON_SEND = %i[!].freeze
def_node_matcher :negate_include_call?, <<~PATTERN
(send (send $!nil? :include? $_) :!)
PATTERN
def on_send(node)
return unless (receiver, obj = negate_include_call?(node))
add_offense(node) do |corrector|
corrector.replace(node, "#{receiver.source}.exclude?(#{obj.source})")
end
end
end
end
end
end