/
next_without_accumulator.rb
55 lines (49 loc) · 1.36 KB
/
next_without_accumulator.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
49
50
51
52
53
54
55
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# Don't omit the accumulator when calling `next` in a `reduce` block.
#
# @example
#
# # bad
#
# result = (1..4).reduce(0) do |acc, i|
# next if i.odd?
# acc + i
# end
#
# @example
#
# # good
#
# result = (1..4).reduce(0) do |acc, i|
# next acc if i.odd?
# acc + i
# end
class NextWithoutAccumulator < Base
MSG = 'Use `next` with an accumulator argument in a `reduce`.'
def on_block(node)
on_block_body_of_reduce(node) do |body|
void_next = body.each_node(:next).find do |n|
n.children.empty? && parent_block_node(n) == node
end
add_offense(void_next) if void_next
end
end
alias on_numblock on_block
private
# @!method on_block_body_of_reduce(node)
def_node_matcher :on_block_body_of_reduce, <<~PATTERN
{
(block (call _recv {:reduce :inject} !sym) _blockargs $(begin ...))
(numblock (call _recv {:reduce :inject} !sym) _argscount $(begin ...))
}
PATTERN
def parent_block_node(node)
node.each_ancestor(:block, :numblock).first
end
end
end
end
end