/
rescued_exceptions_variable_name.rb
112 lines (100 loc) · 2.82 KB
/
rescued_exceptions_variable_name.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
108
109
110
111
112
# frozen_string_literal: true
module RuboCop
module Cop
module Naming
# This cop makes sure that rescued exceptions variables are named as
# expected.
#
# The `PreferredName` config option takes a `String`. It represents
# the required name of the variable. Its default is `e`.
#
# @example PreferredName: e (default)
# # bad
# begin
# # do something
# rescue MyException => exception
# # do something
# end
#
# # good
# begin
# # do something
# rescue MyException => e
# # do something
# end
#
# # good
# begin
# # do something
# rescue MyException => _e
# # do something
# end
#
# @example PreferredName: exception
# # bad
# begin
# # do something
# rescue MyException => e
# # do something
# end
#
# # good
# begin
# # do something
# rescue MyException => exception
# # do something
# end
#
# # good
# begin
# # do something
# rescue MyException => _exception
# # do something
# end
#
class RescuedExceptionsVariableName < Cop
MSG = 'Use `%<preferred>s` instead of `%<bad>s`.'
def on_resbody(node)
name = variable_name(node)
return unless name
return if preferred_name(name).to_sym == name
add_offense(node, location: offense_range(node))
end
def autocorrect(node)
lambda do |corrector|
offending_name = variable_name(node)
preferred_name = preferred_name(offending_name)
corrector.replace(offense_range(node), preferred_name)
node.body&.each_descendant(:lvar) do |var|
next unless var.children.first == offending_name
corrector.replace(var, preferred_name)
end
end
end
private
def offense_range(resbody)
variable = resbody.exception_variable
variable.loc.expression
end
def preferred_name(variable_name)
preferred_name = cop_config.fetch('PreferredName', 'e')
if variable_name.to_s.start_with?('_')
"_#{preferred_name}"
else
preferred_name
end
end
def variable_name(node)
asgn_node = node.exception_variable
return unless asgn_node
asgn_node.children.last
end
def message(node)
offending_name = variable_name(node)
preferred_name = preferred_name(offending_name)
format(MSG, preferred: preferred_name, bad: offending_name)
end
end
end
end
end