Skip to content

Commit f8153ca

Browse files
authored
Merge pull request #881 from gurix/fix/false_positive_for_rails_action_controller_flash_before_render_with_begin
Follow up fix for positive for Rails/ActionControllerFlashBeforeRender in rescue block
2 parents f94b235 + cb2de46 commit f8153ca

File tree

3 files changed

+22
-4
lines changed

3 files changed

+22
-4
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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][])

lib/rubocop/cop/rails/action_controller_flash_before_render.rb

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -69,15 +69,15 @@ def on_send(flash_node)
6969
def followed_by_render?(flash_node)
7070
flash_assigment_node = find_ancestor(flash_node, type: :send)
7171
context = flash_assigment_node
72-
if (if_node = context.each_ancestor(:if).first)
73-
context = if_node
72+
if (node = context.each_ancestor(:if, :rescue).first)
73+
context = node
7474
elsif context.right_siblings.empty?
7575
return true
7676
end
7777
context = context.right_siblings
7878

79-
context.compact.any? do |node|
80-
render?(node)
79+
context.compact.any? do |render_candidate|
80+
render?(render_candidate)
8181
end
8282
end
8383

spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,23 @@ def create
201201
end
202202
RUBY
203203
end
204+
205+
it 'does not register an offense when using `flash` in multiline `rescue` branch before `redirect_to`' do
206+
expect_no_offenses(<<~RUBY)
207+
class HomeController < #{parent_class}
208+
def create
209+
begin
210+
do_something
211+
flash[:alert] = "msg in begin"
212+
rescue
213+
flash[:alert] = "msg in rescue"
214+
end
215+
216+
redirect_to :index
217+
end
218+
end
219+
RUBY
220+
end
204221
end
205222
end
206223

0 commit comments

Comments
 (0)