DRYing up Rails Flash with Flashdance


The scenario: Its 3AM. You've been coding all day and youre just about ready to launch this sweet social networking app for steel workers who love to dance. One last thing - you need to replace all the crappy copy you stuck in to your 'flash' messages with real informative text. "sucesfil post" might make sense to you, but wont make sense to the blue collar guy doing the electric slide all over your server. You go to replace these warnings and feedback messages but theyre all over your code. You think: If Rails is so DRY and the business and display logic are all supposed to be separate, then why am I putting messages that will end up in my views all through my controllers?!

Introducing Flashdance

The get-the-view-out-of-the-controller-so-you-can-rest plugin.

Instead of all-up-in your controller files, messages are stored in a single YAML file:

# in app/views/shared/flash.yml

all_is_good: This is great
this_failed: This failed
using_erb: you are an idiot, <%= @email %>
  subsection: I'm nested
    message: I'm soaking wet


At its most unobtrusive:

# in your controller
  def update
    # . . . booring part where record gets updated
    flash[:warning] = flashdance(:this_failed) #=> This failed

A little nicer:

def update
    # . . .
    flash(:message => 'all_is_good') # YAML entries can be referred to by strings or symbols
    # equivalent to flash[:message] = "This is great"

ERB is evaluated in the context of the controller so you can do fun things like:

  def tell_off_the_spammer
    # . . .
    @email = 'jon@example.com'
    flash(:warning => :using_erb)
    # equivalent to flash[:warning] = "you are an idiot, jon@example.com"

So what if your app is huge and you use these flash thingies all over the place? Your YAML file might get big and unreadable. Well, thats why you can nest! Nested sections are refered to by arrays.

  def make_a_nest
    #  . . .
    flash(:nest => [:section,:subsection])
    # equivalent to flash[:nest] = "I'm nested"

Flashdance automatically checks for entries nested in the controller/action path where you call it from. And heres where you get splashed with that big bucket of water:

class MyController < ApplicationController
  # . . . 
  def my_action
   # . . . where you dance your heart out
   # equivalent to flash[:message] = "I'm soaking wet"

Install it

From subversion:

./script/plugin install -x svn://svn.quirkey.com/quirkey_tools/trunk/flashdance

or Download: flashdance.tar.gz

You can email me at aaron at this domain for bug reports/comments/suggestions - and I'm looking to set up Trac or something else soon.

Photo credit: http://www.flickr.com/photos/tzofia/185003069/

Comments are closed.


QuirkeyBlog is Aaron Quint's perspective on the ongoing adventure of Code, Life, Work and the Web.




QuirkeyBlog is proudly powered by WordPress


  • No categories