Rails Fragment Caching - Testing and time based expiry
Friday, March 23rd, 2007 by Alexander Langin the last days i started implementing caching for autoki.com. my first stop was this excellent rails caching tutorial over at railsenvy.com.
basically, rails offers 3 ways of caching page content:
- page caching: an entire page gets stored on the hard disk and can then be served by apache instead of rails - very fast but almost useless for us, as every page has some dynamic element in this. we still consider it for some ajax calls.
- action caching: also caches the entire page, but it’s still served by rails, which means before_filters for stuff like authnetication still work - still not for us, see above
- fragment caching: as the name implies caches fragments of a page - yay, sounds good
fragment caching
the basics are really easy. first, you simply surround the parts of the page that you want to cache with a <% cache '. this writes the fragment to a file in /tmp/caches and from now on, rails serves this part of the page from the cache.
this alone doesn’t get you any performance improvements yet, because your controller is still loading all the data from the database before rendering the view. to avoid this, you wrap your data loading code into unless read_fragment 'name' ... end blocks - now you page should be running lightning fast already.
the third problem to tackle is to clean the cache at the right time. this can either be done in the controllers by calling expire_fragment 'name' or by using so called sweepers. they are basically observe your models and clean the right fragments on events like after_create - so when you add a new user to the system, you can clean the list of users from the cache.
(more…)




