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.

1 comment:

Yellow Blade said...

Công ty vận chuyển hàng hóa nội địa chúng tôi xin giới thiệu các dịch vụ vận chuyển, dịch vụ ship hàng uy tín để phục vụ nhu cầu Tết của quý khách hàng. Cụ thể chúng tôi sẽ cung cấp dịch vụ chuyển quà tết. Chúng tôi sẽ giúp bạn vận chuyển hàng hóa đến tay người thân, bạn bè ở xa một cách nhanh chóng nhất. Đảm bảo giá cả hợp lý chất lượng dịch vụ tuyệt vời. Ngoài ra chúng tôi còn cung cấp nhiều dịch vụ khác như dịch vụ ship hàng cod, giao hàng cho shop, dịch vụ chuyển phát nhanh trong nước,... Nếu cần chuyển hàng hãy nhớ liên hệ với chúng tôi nhé.