-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
redundant_begin.rb
89 lines (80 loc) · 1.86 KB
/
redundant_begin.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for redundant `begin` blocks.
#
# Currently it checks for code like this:
#
# @example
#
# # bad
# def redundant
# begin
# ala
# bala
# rescue StandardError => e
# something
# end
# end
#
# # good
# def preferred
# ala
# bala
# rescue StandardError => e
# something
# end
#
# # bad
# # When using Ruby 2.5 or later.
# do_something do
# begin
# something
# rescue => ex
# anything
# end
# end
#
# # good
# # In Ruby 2.5 or later, you can omit `begin` in `do-end` block.
# do_something do
# something
# rescue => ex
# anything
# end
#
# # good
# # Stabby lambdas don't support implicit `begin` in `do-end` blocks.
# -> do
# begin
# foo
# rescue Bar
# baz
# end
# end
class RedundantBegin < Base
extend AutoCorrector
MSG = 'Redundant `begin` block detected.'
def on_def(node)
check(node)
end
alias on_defs on_def
def on_block(node)
return if target_ruby_version < 2.5
return if node.send_node.lambda_literal?
return if node.braces?
check(node)
end
private
def check(node)
return unless node.body&.kwbegin_type?
add_offense(node.body.loc.begin) do |corrector|
corrector.remove(node.body.loc.begin)
corrector.remove(node.body.loc.end)
end
end
end
end
end
end