Skip to content

Commit 0d430fe

Browse files
authored
Merge pull request rubocop#844 from koic/fix_a_false_positive_for_rails_action_controller_flash_before_render
[Fix rubocop#843] Fix a false positive for `Rails/ActionControllerFlashBeforeRender`
2 parents fe0ae4d + 1cb5789 commit 0d430fe

File tree

3 files changed

+50
-2
lines changed

3 files changed

+50
-2
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#843](https://github.com/rubocop/rubocop-rails/issues/843): Fix a false positive for `Rails/ActionControllerFlashBeforeRender` when using `flash` in multiline `if` branch before `redirect_to`. ([@koic][])

lib/rubocop/cop/rails/action_controller_flash_before_render.rb

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,9 +69,12 @@ 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-
context = context.parent if context.parent.if_type?
72+
if (if_node = context.each_ancestor(:if).first)
73+
context = if_node
74+
elsif context.right_siblings.empty?
75+
return true
76+
end
7377
context = context.right_siblings
74-
return true if context.empty?
7578

7679
context.compact.any? do |node|
7780
render?(node)

spec/rubocop/cop/rails/action_controller_flash_before_render_spec.rb

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,50 @@ def create
152152
end
153153
RUBY
154154
end
155+
156+
it 'registers an offense when using `flash` in multiline `if` branch before `render_to`' do
157+
expect_offense(<<~RUBY)
158+
class HomeController < #{parent_class}
159+
def create
160+
if condition
161+
do_something
162+
flash[:alert] = "msg"
163+
^^^^^ Use `flash.now` before `render`.
164+
end
165+
166+
render :index
167+
end
168+
end
169+
RUBY
170+
171+
expect_correction(<<~RUBY)
172+
class HomeController < #{parent_class}
173+
def create
174+
if condition
175+
do_something
176+
flash.now[:alert] = "msg"
177+
end
178+
179+
render :index
180+
end
181+
end
182+
RUBY
183+
end
184+
185+
it 'does not register an offense when using `flash` in multiline `if` branch before `redirect_to`' do
186+
expect_no_offenses(<<~RUBY)
187+
class HomeController < #{parent_class}
188+
def create
189+
if condition
190+
do_something
191+
flash[:alert] = "msg"
192+
end
193+
194+
redirect_to :index
195+
end
196+
end
197+
RUBY
198+
end
155199
end
156200
end
157201

0 commit comments

Comments
 (0)