Adding flash message capability to your render calls in Rails
Ruby on Rails 3.x has given us a lot of syntactical sugar. Most of it are pretty small things, things you might not even discover unless someone told you.
One of these things is being able to define flash messages with redirect calls in the controller. In this post I will do a really quick overview of that small feature and replicate it for render calls also – resulting in prettier code.
Let’s get started with code right away – this is how the feature works:
# or with convenience shortcuts :alert and :notice
redirect_to login_path, :notice => "My notice"
redirect_to login_path, :alert => "My alert"
# notice that you can also use the shortcut readers for these
= flash.notice # same as flash[:notice]
= flash.alert # same as flash[:alert]
# and you can also assign with these shortcuts
flash.notice = "foo"
flash.alert = "bar"
Now the common pattern in controllers looks like this:
redirect_to foos_path, :notice => "Foo saved"
else
flash[:alert] = "Some errors occured"
render :action => :new
end
What I want to be able to do is this:
redirect_to foos_path, :notice => "Foo saved"
else
render :action => :new, :alert => "Some errors occured"
end
Adding this functionality is actually pretty simple – we just have to create some code extending the render function.
This next piece of code actually extends the module containing the functionality for the redirect calls.
module Flash
def render(*args)
options = args.last.is_a?(Hash) ? args.last : {}
if alert = options.delete(:alert)
flash[:alert] = alert
end
if notice = options.delete(:notice)
flash[:notice] = notice
end
if other = options.delete(:flash)
flash.update(other)
end
super(*args)
end
end
end
You can place this in an initialize or somewhere in your library directory and explicitly require it. Hope this is helpful for you as much as it is for me!
1 Comment
Brilliant, thanks! There’s a nice symmetry in the calls now.