Categories

Ruby on Rails: Flash Messages and NotifIt

09/12

Spread the word

Recently I saw a tweet from @jquer_in for a jQuery plugin called NotifIt. It’s a simple plugin that lets you pass it a message and some other options and it’ll create a Flash Message to alert your users to information or warning.

If you’ve worked with Rails you should be rather familiar with these. When building web applications we must make sure to help guide the average, probably less than tech savvy user through our application. Let them know that they cannot complete the action they are taking, that the form they submitted successfully saved or any other notification that will give the user a better sense of how to use your application.

I had been waiting for an opportunity to use this plugin and when we started building another Rails application at work, I took the chance to try the plugin out. Often I have a helper method that renders the Flash Message at the top of the page in a standard <p class="flash-msg"></p> and I would have to use custom JavaScript code to animate it out and remove it. Let’s take a look:

The above code, plus a good 20 to 30 lines of CSS is how I have handled these flash messages in the past, but with NotifIt most of the JavaScript is handled for me and so is all of the CSS. Let’s look at a standard alert/flash message using NotifIt:

With CoffeeScript this is becomes three lines of code. Pretty awesome, right?

So how do we integrate it into our already existing Rails app? Simple, our Rails code doesn’t change at all and we cut out the JavaScript we have. Remove the plugin and the code that goes with it. We’ll replace it with our NotifIt code and configurations:

# hide the Rails rendered flash message
$('.flash-msg').hide()
# loop through all flash messages, most of the time you will only have one
$.each $('.flash-msg'), (i, msg) ->
# get the HTML class of our <p> and remove the flash-msg
# === this gives us the priority
klass = $(msg).attr('class').replace /flash-msg\s/, ""
# get the text of the message
text = $(msg).find('strong').text()
# create our NotifIt notification
notif
msg: text
type: klass

That’s pretty much it. Check out the NotifIt example page to see all the options and variations that you can add to customize how you see fit.