lib/rubocop/cop/rails/negate_include.rb in rubocop-rails-2.8.1 vs lib/rubocop/cop/rails/negate_include.rb in rubocop-rails-2.9.0
- old
+ new
@@ -4,34 +4,36 @@
module Cop
module Rails
# This cop enforces the use of `collection.exclude?(obj)`
# over `!collection.include?(obj)`.
#
+ # It is marked as unsafe by default because false positive will occur for
+ # a receiver object that do not have `exclude?` method. (e.g. `IPAddr`)
+ #
# @example
# # bad
# !array.include?(2)
# !hash.include?(:key)
#
# # good
# array.exclude?(2)
# hash.exclude?(:key)
#
- class NegateInclude < Cop
+ 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 $_ :include? $_) :!)
PATTERN
def on_send(node)
- add_offense(node) if negate_include_call?(node)
- end
+ return unless (receiver, obj = negate_include_call?(node))
- def autocorrect(node)
- negate_include_call?(node) do |receiver, obj|
- lambda do |corrector|
- corrector.replace(node, "#{receiver.source}.exclude?(#{obj.source})")
- end
+ add_offense(node) do |corrector|
+ corrector.replace(node, "#{receiver.source}.exclude?(#{obj.source})")
end
end
end
end
end