Rails caching and Javascript pt. 2
In the previous article I showed how to take the advantage of Javascript for page caching.
This cache strategy allows to generate static HTML and allow the web server to serve it, without waste a useless Rails request/response cycle. But, since the cached page is stateless we ask help to Javascript for make it a little bit dynamic.
Flash
All of you has probably noticed that flash object is an enemy of page caching. Let me show you why.
class SessionController
Now suppose the application is in a blank state, when the user hits the dashboard_url, ActionPack will cache the page, including the flash status. This means it will be always rendered, even if the flash will be expired.
The idea is to send the flash contents inside a cookie, when the page finish to load, Javascript will show the message. document.observe(‘dom:loaded’, showFlash);
class SessionController
// cookies.js
var Document = {
cookies: function(document){
return $A(document.cookie.split("; ")).inject($H({}), function(memo, pair){
pair = pair.split('=');
memo.set(pair[0], pair[1]);
return memo;
});
}
};
Object.extend(document, { cookies: Document.cookies.methodize() });
// application.js
function showFlash(){
if(flash = document.cookies().get('flash')){
$('flash').update(escape(flash));
document.cookie = "flash="+escape(flash)+";expires=" + (new Date()).toGMTString();
}
}
When the DOM is loaded showFlash looks for a cookie called flash, if it exist update the page with its contents, then kill it, setting the expiration date on the current time. This because we want to show flash contents only once.