Fragment Cache Expiration in Ruby on Rails

A few days ago I was trying to implement fragment caching with a timed expiration using memcached in rails. I needed a system to cache the results of querying a large number of rss feeds that were being aggregated on the page. Whilst I could have created a system to do this offline and store the results it was easier to just fragment cache and show a stale cache whilst new results were found.

When manually caching or in action caching you simply pass :expires_in => 5.minutes to tell memcached to automatically expire the page after 5 minutes. However this didn’t seem to work with fragment caching, after a tiny bit of digging and error I realised that in order to specify the options hash you have to first specify a key. Since the key is generally made up of the request url I simply used this and appended a unique id for the fragment. Obvious when you think about it I guess!

cache("#{request.url}?fragment", {:expires_in => 60.seconds}) do
  something
end
Advertisements