forked from rubocop/rubocop-performance
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathancestors_include.rb
45 lines (38 loc) · 1.19 KB
/
ancestors_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
43
44
45
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop is used to identify usages of `ancestors.include?` and
# change them to use `<=` instead.
#
# @example
# # bad
# A.ancestors.include?(B)
#
# # good
# A <= B
#
class AncestorsInclude < Cop
include RangeHelp
MSG = 'Use `<=` instead of `ancestors.include?`.'
def_node_matcher :ancestors_include_candidate?, <<~PATTERN
(send (send $_subclass :ancestors) :include? $_superclass)
PATTERN
def on_send(node)
return unless ancestors_include_candidate?(node)
location_of_ancestors = node.children[0].loc.selector.begin_pos
end_location = node.loc.selector.end_pos
range = range_between(location_of_ancestors, end_location)
add_offense(node, location: range)
end
def autocorrect(node)
ancestors_include_candidate?(node) do |subclass, superclass|
lambda do |corrector|
corrector.replace(node, "#{subclass.source} <= #{superclass.source}")
end
end
end
end
end
end
end