1. Skip to navigation
  2. Skip to content

The ELC Community Blog

A knowledge exchange on Ruby on Rails and Agile Development


Conditional Action Caching with Cache_Fu

by Dylan Stamat on June 20, 2007

ELC Plugins

update: http://require.errtheblog.com/plugins/changeset/271
no need for a patch now, it's in the plugin. word up chris !


If you work on a large Rails application, caching is a must.

It would be dreamy to be able to Page Cache everything, but that's usually not an option. Instead, Action and Fragment caching to the rescue. Instead of regurgitating all that is caching, read this article ! Jason and Gregg do an excellent job of explaining the ins-and-outs of Rails caching, and, a slew of other stuff actually (so add them to your RSS reader if you haven't already) :)

Also, most large applications will want to take advantage of Memcached as a cache store. A most excellent plugin that jives oh-so-well with Memcached is Cache_Fu. Take a gander at that link and read up. Also add Chris' blog to your RSS reader if you haven't already :) He produces some high quality goods. He also uses VIm, the editor to trump all editors and IDE's... but that's OT, so... ;)

A great feature that Cache_Fu adds is the ability to set a TTL on your Action caching, ie:

caches_action :index => { :ttl => 10.minutes }

Another nice feature, a patch added by Ilya, handles some of the MIME Type issues you may encounter. Oh... and... add his blog to your RSS reader too. Ok... that will be my last plug, I promise. With his patch, you can do something like:

caches_action :index => { :ttl => 10.minutes, :content_type => 'application/xml' }

Something I wanted to do for a project was serve the Action cached pages only if a certain condition was met (much like what Cache-Filter and Action Cache support.) Promise blatantly broken !... add them to your RSS reader too !

For example, if a user is not logged in, serve the Action Cache... otherwise, go through the entire stack. I created a little patch to do just that, which allows you to pass in conditionals that are evaluated to determine if the cache should be served or skipped, eg:

caches_action :index => { :ttl => 10.minutes, :if => Proc.new {|c| !c.logged_in?} }

Pass in a String, Symbol or Proc, just like some of the ActiveRecord Validations accept.
Hopefully it helps somebody out ! Feedback is more than welcome :)

Get it: conditional_action_caching.diff

See our other Rails Plugins

Comments

Add a comment


home | services | Ruby on Rails Development | code | blog | company