/
redundant_begin.rb
107 lines (95 loc) · 2.29 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# 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
# begin
# do_something
# end
#
# # good
# do_something
#
# # 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)
return unless node.body&.kwbegin_type?
register_offense(node.body)
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?
return unless node.body&.kwbegin_type?
register_offense(node.body)
end
def on_kwbegin(node)
return if node.parent&.assignment?
first_child = node.children.first
return if first_child.rescue_type? || first_child.ensure_type?
register_offense(node)
end
private
def register_offense(node)
add_offense(node.loc.begin) do |corrector|
corrector.remove(node.loc.begin)
corrector.remove(node.loc.end)
end
end
end
end
end
end