-
-
Notifications
You must be signed in to change notification settings - Fork 3k
/
redundant_exception.rb
68 lines (59 loc) · 1.97 KB
/
redundant_exception.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
# frozen_string_literal: true
module RuboCop
module Cop
module Style
# This cop checks for RuntimeError as the argument of raise/fail.
#
# It checks for code like this:
#
# @example
# # Bad
# raise RuntimeError, 'message'
#
# # Bad
# raise RuntimeError.new('message')
#
# # Good
# raise 'message'
class RedundantException < Base
extend AutoCorrector
MSG_1 = 'Redundant `RuntimeError` argument can be removed.'
MSG_2 = 'Redundant `RuntimeError.new` call can be replaced with ' \
'just the message.'
RAISE_METHODS = %i[raise fail].freeze
# Switch `raise RuntimeError, 'message'` to `raise 'message'`, and
# `raise RuntimeError.new('message')` to `raise 'message'`.
def on_send(node)
return unless RAISE_METHODS.include?(node.method_name)
fix_exploded(node) || fix_compact(node)
end
def fix_exploded(node)
exploded?(node) do |command, message|
add_offense(node, message: MSG_1) do |corrector|
if node.parenthesized?
corrector.replace(node,
"#{command}(#{message.source})")
else
corrector.replace(node,
"#{command} #{message.source}")
end
end
end
end
def fix_compact(node)
compact?(node) do |new_call, message|
add_offense(node, message: MSG_2) do |corrector|
corrector.replace(new_call, message.source)
end
end
end
def_node_matcher :exploded?, <<~PATTERN
(send nil? ${:raise :fail} (const {nil? cbase} :RuntimeError) $_)
PATTERN
def_node_matcher :compact?, <<~PATTERN
(send nil? {:raise :fail} $(send (const {nil? cbase} :RuntimeError) :new $_))
PATTERN
end
end
end
end