From fd10b2770cdb0ae059002949cd9085f7b4c4e934 Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Mon, 4 Mar 2024 13:42:34 +0100 Subject: [PATCH] [Fix #1244] Fix a false positive for `Rails/ActionControllerFlashBeforeRender` when returning `redirect_to` --- ...ails_action_controller_flash_before_render.md | 1 + .../action_controller_flash_before_render.rb | 2 ++ ...action_controller_flash_before_render_spec.rb | 16 ++++++++++++++++ 3 files changed, 19 insertions(+) create mode 100644 changelog/fix_a_false_positive_for_rails_action_controller_flash_before_render.md diff --git a/changelog/fix_a_false_positive_for_rails_action_controller_flash_before_render.md b/changelog/fix_a_false_positive_for_rails_action_controller_flash_before_render.md new file mode 100644 index 0000000000..6bcb5dc3bd --- /dev/null +++ b/changelog/fix_a_false_positive_for_rails_action_controller_flash_before_render.md @@ -0,0 +1 @@ +* [#1244](https://github.com/rubocop/rubocop-rails/issues/1244): Fix a false positive for `Rails/ActionControllerFlashBeforeRender` when returning `redirect_to`. ([@earlopain][]) diff --git a/lib/rubocop/cop/rails/action_controller_flash_before_render.rb b/lib/rubocop/cop/rails/action_controller_flash_before_render.rb index 390ef37482..0c1c3b03d8 100644 --- a/lib/rubocop/cop/rails/action_controller_flash_before_render.rb +++ b/lib/rubocop/cop/rails/action_controller_flash_before_render.rb @@ -99,6 +99,8 @@ def instance_method_or_block?(node) def use_redirect_to?(context) context.right_siblings.compact.any? do |sibling| + # Unwrap `return redirect_to :index` + sibling = sibling.children.first if sibling.return_type? && sibling.children.count == 1 sibling.send_type? && sibling.method?(:redirect_to) end end diff --git a/spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb b/spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb index 4e1dd01a20..4704d07a29 100644 --- a/spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb +++ b/spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb @@ -312,4 +312,20 @@ def create RUBY end end + + context 'when using `flash` after `render` and returning `redirect_to` in condition block' do + it 'does not register an offense' do + expect_no_offenses(<<~RUBY) + class HomeController < ApplicationController + def create + if condition + flash[:alert] = "msg" + return redirect_to "https://www.example.com/" + end + render :index + end + end + RUBY + end + end end