Addicted To Caching
September 11th, 2006
There are three types of caching built into Rails (Page, Action and Fragment). Others have written about them in detail so I won’t here. What I will speak of is how I handled caching on the Notre Dame Web Group’s latest creation.
Page Caching
Page caching is very agressive. All that is required to use page caching in a Ruby on Rails application is to add a call (caches_page :index) in your controller. Yep, that’s it. Not only is it instant, but it caches the entire page and stores it as an html file in your public folder. I remember learning about page caching in the Chicago Rails Studio and having one of those, that is so simple I can’t believe I didn’t think of that moments.
I knew the Forum’s website would receive far more traffic than updates, so I decided to use full page caching and then blow away the entire cache whenever certain model records were modified. This approach solved the issue of having to figure out what pages needed to be expired and what pages didn’t. What evolved is a really simple plugin which worked great, so I thought I would share it.
How To Use
-
script/plugin install http://svn.addictedtonew.com/public/plugins/addicted_to_caching/ - Check the list of protected entries in the plugin and make sure that it won’t delete anything in your public folder that you need.
- Add acts_as_cache_clearer to any model that should clear the cache if any of its records are modified.
- Generously add caches_page to all your controllers where needed
How It Works
Because page caching uses the public folder to store it’s cached files, all that is need to clear the entire cache is to remove each entry (file or folder) in the public folder that is not suppose to exist. The plugin contains a PROTECTED_ENTRIES array which determines which entries are not to be deleted in the public folder.