/
action_controller_flash_before_render.rb
73 lines (59 loc) · 1.99 KB
/
action_controller_flash_before_render.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
# frozen_string_literal: true
module RuboCop
module Cop
module Rails
# Using `flash` assignment before `render` will persist the message for too long.
# Check https://guides.rubyonrails.org/action_controller_overview.html#flash-now
#
# @safety
# This cop's autocorrection is unsafe because it replaces `flash` by `flash.now`.
# Even though it is usually a mistake, it might be used intentionally.
#
# @example
# # bad
# flash[:alert] = "Warning!"
# render :index
#
# # good
# flash.now[:alert] = "Warning!"
# render :index
#
class ActionControllerFlashBeforeRender < Base
extend AutoCorrector
MSG = 'Use `flash.now` before `render`.'
def_node_search :flash_assignment?, <<~PATTERN
^(send (send nil? :flash) :[]= ...)
PATTERN
def_node_search :render?, <<~PATTERN
(send nil? :render ...)
PATTERN
def_node_search :action_controller?, <<~PATTERN
{
(const nil? :ApplicationController)
(const (const nil? :ActionController) :Base)
}
PATTERN
RESTRICT_ON_SEND = [:flash].freeze
def on_send(node)
expression = flash_assignment?(node)
return unless expression
context = node.each_ancestor(:begin).first
return unless context
siblings = context.descendants
return unless siblings.any? { |sibling| render?(sibling) }
return unless inherit_action_controller_base?(node)
add_offense(node) do |corrector|
corrector.replace(node, 'flash.now')
end
end
def inherit_action_controller_base?(node)
class_node = node.each_ancestor(:class).first
return unless class_node
def_node = node.each_ancestor(:def).first
return unless def_node
action_controller?(class_node)
end
end
end
end
end