Extending the Life of a Flash Message
Problem
You've created a flash message and are displaying it to the user. You'd like to extend the life of that message for one more request than would normally exist.
Solution
You can call the keep method of the Flash class on a specific entry, or the entire contents of the flash hash. This technique is useful for redisplaying flash messages in subsequent requests without explicitly recreating them.
To demonstrate this, create the following Rental Controller:
app/controllers/rental_controller.rb:
class RentalController < ApplicationController
def step_one
flash.now[:reminder] = 'There is a $20 fee for late payments.'
flash.keep(:reminder)
end
def step_two
end
def step_three
end end
And create the following three views:
app/views/rental/step_one.rhtml:
<h1>Step one!</h1>
<% if flash[:reminder] %>
<p ><%= flash[:reminder] %></p>
<% end %>
<a href="step_two">step_two</a>
app/views/rental/step_two.rhtml:
<h1>Step two!</h1>
<% if flash[:reminder] %>
<p ><%= flash[:reminder] %></p>
<% end %>
<a href="step_three">step_tree</a>
app/views/rental/step_three.rhtml:
<h1>Step three!</h1>
<% if flash[:reminder] %>
<p ><%= flash[:reminder] %></p>
<% end %>
<a href="step_one">step_one</a>
Discussion
As you can see in the solution, the controller creates a flash message only in the action called step_one.
From a browser, in the first step you see the reminder on the screen. When you click on the link at the bottom of the page, you call step_two. Now the flash message is shown a second time.
Step three is like step two, but we didn't call the flash.keep in this method, and the message doesn't reappear. The keep method holds the reminder for only one request.
See Also
|