Skip to content

Commit

Permalink
[Fix #909] Fix a false positive for `Rails/ActionControllerFlashBefor…
Browse files Browse the repository at this point in the history
…eRender`

Fixes #909.

This PR fixes a false positive for `Rails/ActionControllerFlashBeforeRender`
when using `flash` before `redirect_to` in `if` branch.
  • Loading branch information
koic committed Feb 22, 2023
1 parent 81b0fdc commit ad0fec1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +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][])
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@ def followed_by_render?(flash_node)
flash_assignment_node = find_ancestor(flash_node, type: :send)
context = flash_assignment_node
if (node = context.each_ancestor(:if, :rescue).first)
return false if use_redirect_to?(context)

context = node
elsif context.right_siblings.empty?
return true
Expand All @@ -95,6 +97,12 @@ def instance_method_or_block?(node)
def_node || block_node
end

def use_redirect_to?(context)
context.right_siblings.compact.any? do |sibling|
sibling.send_type? && sibling.method?(:redirect_to)
end
end

def find_ancestor(node, type:)
node.each_ancestor(type).first
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,23 @@ def create
RUBY
end

it 'does not register an offense when using `flash` before `redirect_to` in `if` branch' do
expect_no_offenses(<<~RUBY)
class HomeController < #{parent_class}
def create
if condition
flash[:alert] = "msg"
redirect_to :index
return
end
render :index
end
end
RUBY
end

it 'does not register an offense when using `flash` in multiline `rescue` branch before `redirect_to`' do
expect_no_offenses(<<~RUBY)
class HomeController < #{parent_class}
Expand Down

0 comments on commit ad0fec1

Please sign in to comment.