diff --git a/changelog/fix_an_error_for_rails_action_controller_flash_before_render.md b/changelog/fix_an_error_for_rails_action_controller_flash_before_render.md new file mode 100644 index 0000000000..03ec9d040b --- /dev/null +++ b/changelog/fix_an_error_for_rails_action_controller_flash_before_render.md @@ -0,0 +1 @@ +* [#1539](https://github.com/rubocop/rubocop-rails/issues/1539): Fix an error in `Rails/ActionControllerFlashBeforeRender` when `flash` is used inside a block followed by method chaining. ([@koic][]) 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 bab9011c94..9980e1ee41 100644 --- a/lib/rubocop/cop/rails/action_controller_flash_before_render.rb +++ b/lib/rubocop/cop/rails/action_controller_flash_before_render.rb @@ -98,7 +98,9 @@ def instance_method_or_block?(node) end def use_redirect_to?(context) - context.right_siblings.compact.any? do |sibling| + context.right_siblings.any? do |sibling| + next unless sibling.is_a?(AST::Node) + # Unwrap `return redirect_to :index` sibling = sibling.children.first if sibling.return_type? && sibling.children.one? sibling.send_type? && sibling.method?(:redirect_to) 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 fa1e45097f..3a8a662484 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 @@ -427,4 +427,16 @@ def create RUBY end end + + context 'when `flash` is used inside a block followed by method chaining' do + it 'does not register an offense and corrects' do + expect_no_offenses(<<~RUBY) + class NonController < ApplicationRecord + before_action do + flash[:notice] = 'hello' + end.do_something + end + RUBY + end + end end