I’ve been doing some Rails work recently and one of the things that I’ve found to be a nice aesthetic add-on is putting some nicer flash messages in.
Over at dzone.com there is an example which I’ve worked off of – http://snippets.dzone.com/posts/show/3145
The example is as follows. Add this section to your application_helper.rb
In your CSS file you now add the settings to style your messages. Note that my examples assume some images are present so add images as you wish for within the message:
.flash_notice {
BORDER-RIGHT: #090 4px solid; PADDING-RIGHT: 10px; BACKGROUND-POSITION: 5px 50%; BORDER-TOP: #090 4px solid; PADDING-LEFT: 10px; BACKGROUND-IMAGE: url(/images/icon_success_lrg.gif); PADDING-BOTTOM: 10px; MARGIN: 2px; BORDER-LEFT: #090 4px solid; TEXT-INDENT: 40px; PADDING-TOP: 10px; BORDER-BOTTOM: #090 4px solid; BACKGROUND-REPEAT: no-repeat
}
.flash_warning {
BORDER-RIGHT: #c60 4px solid; PADDING-RIGHT: 10px; BACKGROUND-POSITION: 5px 50%; BORDER-TOP: #c60 4px solid; PADDING-LEFT: 10px; BACKGROUND-IMAGE: url(/images/icon_warning_lrg.gif); PADDING-BOTTOM: 10px; MARGIN: 2px; BORDER-LEFT: #c60 4px solid; TEXT-INDENT: 40px; PADDING-TOP: 10px; BORDER-BOTTOM: #c60 4px solid; BACKGROUND-REPEAT: no-repeat
}
.flash_error {
BORDER-RIGHT: #f00 4px solid; PADDING-RIGHT: 10px; BACKGROUND-POSITION: 5px 50%; BORDER-TOP: #f00 4px solid; PADDING-LEFT: 10px; BACKGROUND-IMAGE: url(/images/icon_error_lrg.gif); PADDING-BOTTOM: 10px; MARGIN: 2px; BORDER-LEFT: #f00 4px solid; TEXT-INDENT: 40px; PADDING-TOP: 10px; BORDER-BOTTOM: #f00 4px solid; BACKGROUND-REPEAT: no-repeat
}
In your view, which in my case is the views/layouts/application.html.erb (same for Rails 2 or 3) I have added this where I want my flash notices:
<%= show_flash %>
If you are running Rails 3 there are two additional steps you need to take. First you need to change the code on your view to display as follows:
<%= raw show_flash %>
Note that under Rails 3 the flash will render the html code as text rather than as the raw html. By adding the raw statement you fix this issue and it will render correctly.
The second change you want to make is for your scaffolds. By default the show.html.erb file already contains a message section. If you leave this in place you will end up with 2 flash messages on each render of the show action. To fix this, go into the show.html.erb under your app/view/scaffoldname/ folder and remove this line:
<p id=”notice”><%= notice %></p>
Here are the 3 image files that I’ve used as referenced in the CSS
That’s my hopefully useful Rails tip of the day!