Wednesday, January 7, 2009

I Love Rails - Rails Caching Even On Windows!

I escaped a $999 Mac purchase last week. I thought I'd need it for development. While I should have one, that's not a purchase that's at all likely. Instead, I'm pushing code to our dev server and testing there. At least for the code that requires workling and starling. And I'm glad. Because I'm not entirely sure I'm ready for a Mac. It's a commitment.

Sorry for the digression. Today I started implementing Rails caching as well as memcache. And I gotta say, I love it! Rails comes with 4 flavors of caching, page caching, action caching, fragment caching, and ActiveRecord query caching (on by default).

They're sort of self explanatory. Page caching caches pages. This is really useful for stuff that doesn't change much. While the point of serving static pages by Rails at all is debatable, what's not debatable is how easy it is to cache them. No more going to the controller. With the cache, it'll be stored in a local .html file and served by your little Mongrel. Then there's action caching. You can cache specific actions, which will cause your filters to run, enabling login/authentication, etc. But the actions themselves are cached. Good for static or mostly static pages that are beyond a login. Next is fragment caching, which enables caching for fragments of your code... like a view fragment that loads up countries or something like that.

Then I implemented memcache, because I wanted to do some model caching - caching that would extend beyond the four cases I just listed. In other words, I want to store objects in the cache - and memcache is perfect for that.

In any event, the process is simple:
For Rails caching of my static pages, all I do is add this: caches_page :about (this is the name of the method that I want cached)

For memcache, I create a class method: Rails.cache.fetch("Model.#{type_id}") { Model.find(type_id)}

The fetch fetches the hash value listed in the parentheses. If it's not there, it runs the block following. Dead simple.

No comments: