/
reverse_each.rb
48 lines (40 loc) · 1.21 KB
/
reverse_each.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
# frozen_string_literal: true
module RuboCop
module Cop
module Performance
# This cop is used to identify usages of `reverse.each` and
# change them to use `reverse_each` instead.
#
# @example
# # bad
# [].reverse.each
#
# # good
# [].reverse_each
class ReverseEach < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use `reverse_each` instead of `reverse.each`.'
RESTRICT_ON_SEND = %i[each].freeze
UNDERSCORE = '_'
def_node_matcher :reverse_each?, <<~MATCHER
(send $(send _ :reverse) :each)
MATCHER
def on_send(node)
reverse_each?(node) do |receiver|
location_of_reverse = receiver.loc.selector.begin_pos
end_location = node.loc.selector.end_pos
range = range_between(location_of_reverse, end_location)
add_offense(range) do |corrector|
corrector.replace(replacement_range(node), UNDERSCORE)
end
end
end
private
def replacement_range(node)
range_between(node.loc.dot.begin_pos, node.loc.selector.begin_pos)
end
end
end
end
end