Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails page caching and flash messages

I'm pretty sure I can page cache the vast majority of my site but the one thing preventing me from doing so is that my flash messages will not show, or they'll show at the wrong time.

One thing I'm considering is writing the flash message to a cookie, reading it and displaying it via javascript and clearing the cookie once the message has been displayed. Has anyone had any success doing this or are there better methods?

Thanks.

like image 983
KJF Avatar asked Feb 26 '10 17:02

KJF


1 Answers

Cacheable flash do this:

in your application controller:

after_filter :write_flash_to_cookie


def write_flash_to_cookie
    cookie_flash = cookies['flash'] ? JSON.parse(cookies['flash']) : {}

    flash.each do |key, value|
        if cookie_flash[key.to_s].blank?
            cookie_flash[key.to_s] = value
        else
            cookie_flash[key.to_s] << "<br/>#{value}"
        end
     end

    cookies['flash'] = cookie_flash.to_json
    flash.clear
end

and then read "flash" cookie via Javascript and insert the message inside the HTML

like image 140
VMOrtega Avatar answered Oct 26 '22 11:10

VMOrtega