/
nil_lambda.rb
70 lines (62 loc) · 1.64 KB
/
nil_lambda.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# Checks for lambdas and procs that always return nil,
# which can be replaced with an empty lambda or proc instead.
#
# @example
# # bad
# -> { nil }
#
# lambda do
# next nil
# end
#
# proc { nil }
#
# Proc.new do
# break nil
# end
#
# # good
# -> {}
#
# lambda do
# end
#
# -> (x) { nil if x }
#
# proc {}
#
# Proc.new { nil if x }
#
class NilLambda < Base
extend AutoCorrector
include RangeHelp
MSG = 'Use an empty %<type>s instead of always returning nil.'
# @!method nil_return?(node)
def_node_matcher :nil_return?, <<~PATTERN
{ ({return next break} nil) (nil) }
PATTERN
def on_block(node) # rubocop:disable InternalAffairs/NumblockHandler
return unless node.lambda_or_proc?
return unless nil_return?(node.body)
message = format(MSG, type: node.lambda? ? 'lambda' : 'proc')
add_offense(node, message: message) do |corrector|
autocorrect(corrector, node)
end
end
private
def autocorrect(corrector, node)
range = if node.single_line?
range_with_surrounding_space(node.body.source_range)
else
range_by_whole_lines(node.body.source_range, include_final_newline: true)
end
corrector.remove(range)
end
end
end
end
end