Chronicling my experiences with ruby on rails, web application development/management.

Wednesday, July 1, 2009

30 days of Rails - Handling Flash Messages

So, here i am trying to expand my closed world beyond Restful_authentication and well, basically any other technoweenie based plugin. I try my hand at Clearance

Clearance is a thoughtbot based gem which authenticates users in your web app. Out of the box, it only allows for email addresses as the login ID, which is fine for my stupid app i'm making.

However, in all my years of scaffolding, i guess i've only really used flash[:notice] for displaying my flash messages on an overall layout level. Clearance has flash[:success] and flash[:error].

The reason i found this out is because my clearance_features weren't working and i was getting 8 failures, due to the fact that I was only displaying flash[:notice]. A win for BDD i tell ya.

Gee mister, how'd you fix it

Like all expert coders, i went to the one place I can trust. Twitter. I sent out a tweet which read: twitter ruby fun: lame, hack or on track? < % = flash[:notice] ||flash[:success] || flash[:failure] % >

Most people hated this code, which is fine, as that is what i wanted to hear. While it will work, if i had a need for two flash messages at once, or if i needed to expand my flash message symbols, i'd be fucked. Enter @heycarsten

This dude turned me onto a pretty sweet gist he wrote up for me. A thousand thank you sir's to him.

Gist... Break it down hammer style.

Well everytime you see me, the hammer is on dootie...ok, hammer time is over.

  1. Create a helper called flash_helper.rb and paste this gist into it.
  2. inside the layouts directory, create a folder called partials and a partial inside of your layouts folder called /layouts/partials/flash_message.html.erb.
  3. Paste this into it(stupid stupid blogger's formatting sucks ass... so you'll have to take the spaces out)
    < p id=< % = "flash_#{type}" % > >
    < % = flash[type.to_sym] % >
    < /p >

  4. In your application_controller.html.erb you'll need to add this code to display your new fancy flash messages:
    < % = flash_messages % >

  5. In your css file, now you can create styles with the id flash_whatever. I used #flash_error{background-color: red;}, etc...If you are new to css, learn up on it son.

Yeah for heycarsten and many thanks to him for allowing me to post this code.P.s., i apologize for this shitty code formatting. blogspot sucks ass.

No comments:

Post a Comment