/
ensure_return.rb
61 lines (58 loc) · 1.33 KB
/
ensure_return.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
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for `return` from an `ensure` block.
# `return` from an ensure block is a dangerous code smell as it
# will take precedence over any exception being raised,
# and the exception will be silently thrown away as if it were rescued.
#
# If you want to rescue some (or all) exceptions, best to do it explicitly
#
# @example
#
# # bad
#
# def foo
# do_something
# ensure
# cleanup
# return self
# end
#
# @example
#
# # good
#
# def foo
# do_something
# self
# ensure
# cleanup
# end
#
# # also good
#
# def foo
# begin
# do_something
# rescue SomeException
# # Let's ignore this exception
# end
# self
# ensure
# cleanup
# end
class EnsureReturn < Base
extend AutoCorrector
include RangeHelp
MSG = 'Do not return from an `ensure` block.'
def on_ensure(node)
node.body&.each_node(:return) do |return_node|
add_offense(return_node)
end
end
end
end
end
end