forked from github/rubocop-github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrails_controller_render_shorthand.rb
51 lines (42 loc) · 1.38 KB
/
rails_controller_render_shorthand.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
# frozen_string_literal: true
require "rubocop"
module RuboCop
module Cop
module GitHub
class RailsControllerRenderShorthand < Cop
MSG = "Prefer `render` template shorthand"
def_node_matcher :render_with_options?, <<-PATTERN
(send nil? :render (hash $...))
PATTERN
def_node_matcher :action_key?, <<-PATTERN
(pair (sym {:action :template}) $({str sym} _))
PATTERN
def_node_matcher :str, <<-PATTERN
({str sym} $_)
PATTERN
def investigate(*)
@autocorrect = {}
end
def autocorrect(node)
@autocorrect[node]
end
def on_send(node)
if option_pairs = render_with_options?(node)
option_pairs.each do |pair|
if value_node = action_key?(pair)
comma = option_pairs.length > 1 ? ", " : ""
corrected_source = node.source
.sub(/#{pair.source}(,\s*)?/, "")
.sub("render ", "render \"#{str(value_node)}\"#{comma}")
@autocorrect[node] = lambda do |corrector|
corrector.replace(node.source_range, corrected_source)
end
add_offense(node, location: :expression, message: "Use `#{corrected_source}` instead")
end
end
end
end
end
end
end
end