Skip to content

Commit

Permalink
[Fix rubocop#843] Fix a false positive for `Rails/ActionControllerFla…
Browse files Browse the repository at this point in the history
…shBeforeRender`

Fixes rubocop#843.

This PR fixes a false positive for `Rails/ActionControllerFlashBeforeRender`
when using `flash` in the multiline statements as `if` branch before `redirect_to`.
  • Loading branch information
koic committed Oct 27, 2022
1 parent fe0ae4d commit 4268c25
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,12 @@ def on_send(flash_node)
def followed_by_render?(flash_node)
flash_assigment_node = find_ancestor(flash_node, type: :send)
context = flash_assigment_node
context = context.parent if context.parent.if_type?
if (if_node = context.each_ancestor(:if).first)
context = if_node
elsif context.right_siblings.empty?
return true
end
context = context.right_siblings
return true if context.empty?

context.compact.any? do |node|
render?(node)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,50 @@ def create
end
RUBY
end

it 'registers an offense when using `flash` in multiline `if` branch before `render_to`' do
expect_offense(<<~RUBY)
class HomeController < #{parent_class}
def create
if condition
do_something
flash[:alert] = "msg"
^^^^^ Use `flash.now` before `render`.
end
render :index
end
end
RUBY

expect_correction(<<~RUBY)
class HomeController < #{parent_class}
def create
if condition
do_something
flash.now[:alert] = "msg"
end
render :index
end
end
RUBY
end

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

Expand Down

0 comments on commit 4268c25

Please sign in to comment.