/
action_controller_flash_before_render.rb
54 lines (45 loc) · 1.44 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
# 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
RESTRICT_ON_SEND = [:flash].freeze
def on_send(node)
expression = flash_assignment?(node)
return unless expression
context = node.parent.parent
return unless context
siblings = context.descendants
return unless siblings.any? { |sibling| render?(sibling) }
add_offense(node) do |corrector|
corrector.replace(node, 'flash.now')
end
end
end
end
end
end