forked from rubocop/rubocop-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsafe_navigation.rb
86 lines (75 loc) · 2.29 KB
/
safe_navigation.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
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# This cop converts usages of `try!` to `&.`. It can also be configured
# to convert `try`. It will convert code to use safe navigation.
#
# @example ConvertTry: false (default)
# # bad
# foo.try!(:bar)
# foo.try!(:bar, baz)
# foo.try!(:bar) { |e| e.baz }
#
# foo.try!(:[], 0)
#
# # good
# foo.try(:bar)
# foo.try(:bar, baz)
# foo.try(:bar) { |e| e.baz }
#
# foo&.bar
# foo&.bar(baz)
# foo&.bar { |e| e.baz }
#
# @example ConvertTry: true
# # bad
# foo.try!(:bar)
# foo.try!(:bar, baz)
# foo.try!(:bar) { |e| e.baz }
# foo.try(:bar)
# foo.try(:bar, baz)
# foo.try(:bar) { |e| e.baz }
#
# # good
# foo&.bar
# foo&.bar(baz)
# foo&.bar { |e| e.baz }
class SafeNavigation < Base
include RangeHelp
extend AutoCorrector
MSG = 'Use safe navigation (`&.`) instead of `%<try>s`.'
RESTRICT_ON_SEND = %i[try try!].freeze
def_node_matcher :try_call, <<~PATTERN
(send !nil? ${:try :try!} $_ ...)
PATTERN
def on_send(node)
try_call(node) do |try_method, dispatch|
return if try_method == :try && !cop_config['ConvertTry']
return unless dispatch.sym_type? && dispatch.value.match?(/\w+[=!?]?/)
add_offense(node, message: format(MSG, try: try_method)) do |corrector|
autocorrect(corrector, node)
end
end
end
private
def autocorrect(corrector, node)
method_node, *params = *node.arguments
method = method_node.source[1..-1]
range = range_between(node.loc.dot.begin_pos, node.loc.expression.end_pos)
corrector.replace(range, replacement(method, params))
end
def replacement(method, params)
new_params = params.map(&:source).join(', ')
if method.end_with?('=')
"&.#{method[0...-1]} = #{new_params}"
elsif params.empty?
"&.#{method}"
else
"&.#{method}(#{new_params})"
end
end
end
end
end
end