diff --git a/changelog/fix_false_positive_action_controller_flash_before_render_after_rescue.md b/changelog/fix_false_positive_action_controller_flash_before_render_after_rescue.md new file mode 100644 index 0000000000..0167185fc8 --- /dev/null +++ b/changelog/fix_false_positive_action_controller_flash_before_render_after_rescue.md @@ -0,0 +1 @@ +* [#881](https://github.com/rubocop/rubocop-rails/pull/881): Fix a false positive for `Rails/ActionControllerFlashBeforeRender` when using `flash` in multiline `rescue` branch before `redirect_to`. ([@gurix][]) 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 2e45be2ba9..4a30ac97e1 100644 --- a/lib/rubocop/cop/rails/action_controller_flash_before_render.rb +++ b/lib/rubocop/cop/rails/action_controller_flash_before_render.rb @@ -69,15 +69,15 @@ def on_send(flash_node) def followed_by_render?(flash_node) flash_assigment_node = find_ancestor(flash_node, type: :send) context = flash_assigment_node - if (if_node = context.each_ancestor(:if).first) - context = if_node + if (node = context.each_ancestor(:if, :rescue).first) + context = node elsif context.right_siblings.empty? return true end context = context.right_siblings - context.compact.any? do |node| - render?(node) + context.compact.any? do |render_candidate| + render?(render_candidate) 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 b8546a49cf..9b91562bcc 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 @@ -201,6 +201,23 @@ def create 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} + def create + begin + do_something + flash[:alert] = "msg in begin" + rescue + flash[:alert] = "msg in rescue" + end + + redirect_to :index + end + end + RUBY + end end end