Skip to content

Commit ad0fec1

Browse files
committed
[Fix #909] Fix a false positive for Rails/ActionControllerFlashBeforeRender
Fixes #909. This PR fixes a false positive for `Rails/ActionControllerFlashBeforeRender` when using `flash` before `redirect_to` in `if` branch.
1 parent 81b0fdc commit ad0fec1

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#909](https://github.com/rubocop/rubocop-rails/issues/909): Fix a false positive for `Rails/ActionControllerFlashBeforeRender` when using `flash` before `redirect_to` in `if` branch. ([@koic][])

lib/rubocop/cop/rails/action_controller_flash_before_render.rb

+8
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,8 @@ def followed_by_render?(flash_node)
7070
flash_assignment_node = find_ancestor(flash_node, type: :send)
7171
context = flash_assignment_node
7272
if (node = context.each_ancestor(:if, :rescue).first)
73+
return false if use_redirect_to?(context)
74+
7375
context = node
7476
elsif context.right_siblings.empty?
7577
return true
@@ -95,6 +97,12 @@ def instance_method_or_block?(node)
9597
def_node || block_node
9698
end
9799

100+
def use_redirect_to?(context)
101+
context.right_siblings.compact.any? do |sibling|
102+
sibling.send_type? && sibling.method?(:redirect_to)
103+
end
104+
end
105+
98106
def find_ancestor(node, type:)
99107
node.each_ancestor(type).first
100108
end

spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb

+17
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,23 @@ def create
202202
RUBY
203203
end
204204

205+
it 'does not register an offense when using `flash` before `redirect_to` in `if` branch' do
206+
expect_no_offenses(<<~RUBY)
207+
class HomeController < #{parent_class}
208+
def create
209+
if condition
210+
flash[:alert] = "msg"
211+
redirect_to :index
212+
213+
return
214+
end
215+
216+
render :index
217+
end
218+
end
219+
RUBY
220+
end
221+
205222
it 'does not register an offense when using `flash` in multiline `rescue` branch before `redirect_to`' do
206223
expect_no_offenses(<<~RUBY)
207224
class HomeController < #{parent_class}

0 commit comments

Comments
 (0)