Written by Sean Behan on Fri Nov 01st 2013

Session based flash messages are fairly common in web apps. They work well when you have a temporary status to report back to the user, such as successfully saving a form.

If you use Rails it comes with the Framework. If you are using Sinatra there are a few Rack based plugins. But it's fairly trivial to write yourself. And you don't add a lot of complexity to your project.

The trick is to unset the key when you get the value for display. This way no message will be seen on the next request.

# Simple flash messages
# flash = FlashMessage.new(session)
# flash.message = 'hello world'
# flash.message # => 'hello world'
# flash.message # => nil
class FlashMessage
    def initialize(session)
        @session ||= session
    end

    def message=(message)
        @session[:flash] = message
    end

    def message
        message = @session[:flash] #tmp get the value
        @session[:flash] = nil # unset the value
        message # display the value
    end
end

If you're using Sinatra, in the helpers block you can create a method for quick access in your routes and views.

configure do
    enable :sessions
end

helpers do
    def flash
        @flash ||= FlashMessage.new(session)
    end
end

# a few routes
get '/' do
    flash.message = 'Hello World'
    redirect '/flash'
end

get '/flash' do
 erb :index
end

# views/flash.erb
<%= flash.message %>

As you can see it's pretty straight forward. You can also be a little more creative if you take this approach and implement it yourself.

For instance, you could additional methods for different types of flash messages with logging. Or maybe you could add a second parameter, a counter, that will display a flash message n number of times before popping it off the stack...

flash.message=('Remember to reset your password', 10)


Tagged with..
#Ruby #Sinatra #Flash Messages #Roll Your Own

Just finishing up brewing up some fresh ground comments...