Rails’ Page Caching with Multiple Formats in respond_to

One of the apps I’m working on was using Rails’ caches_page to speed up performance and reduce server load.

It worked great until we added new formats via within the respond_to block. If there wasn’t a format specified in the request – the caches would get all messed up. Well sometimes. Making it a difficult issue isolate.

I found lots of articles on caching 1 format and not another – even Rails’ documentation illustrates how to do that.

But I wanted to cache all the formats.

The most reliably way I’ve been able to accomplish this is by explicitly declaring the format-specific location for the caches. Like this:


respond_to do |format|
format.html {
render :layout => 'application', :content_type => "text/html"
cache_page(@response, "/index.html")
}


format.rss {
render :layout => false, :content_type => "application/rss+xml"
cache_page(@response, "/index.rss")
}


format.iphone {
render :layout => 'iphone', :content_type => "text/html"
cache_page(@response, "/index.iphone")
}
end

Note the render lines, they seem to be required for the @response to properly populate.

This solves the correct creation of the format-specific page caching, there’s still the issue of the web server (Nginx, Apache) knowing which cached file to serve.

Whatever checks Rails’ is doing (i.e. Are you an iPhone?, etc) to generate the correct cache need to be duplicated in the web server and mapped to the corresponding cache file.

Personally, this seems like a overly-complex solution for an issue I hadn’t assumed would exist. What am I missing?