Ruby on Rails Method Caching
While investigating caching techniques for Ruby on Rails I found the most promising to be cachesrb, which allows controller method-level caching.
I found it from this from the Rails Caching post by Robert R Evans. Rails page- and action-level caching are often too restrictive, as they don’t work well with things like query parameters or pages requiring a flash. Fragment caching is too low-level, requiring a high degree of manual intervention to be used effectively. Method caching seems to be just what we need.
It looks like the project was once active at RubyForge and is maybe now active at githug.
The wiki for the project, once available at http://pad.verbdev.com/cachesrb/, now loads only a blank page. Google Cache revels it once contained this content:
Caches.rb
Caches.rb is a simple Ruby library that allows you to let some class methods be cached.
- How To Get (download options)
Please note that this documentation is not double checked yet
Ongoing changes
http://rashkovskii.com/articles/2007/2/28/new-experimental-caches-rb
http://rashkovskii.com/articles/2007/4/1/ongoing-improvements-in-caches-rb
Don’t tell, show me!
OK.
Let’s assume you have an expensive method, and you want to cache it for one minute (default timeout):
def expensive_method
...
end
caches :expensive_method
When you will call your expensive method first time, it will be executed. For the next 60 seconds any call to this method will return cached value.
Want to invalidate it earlier? No problem:
...some code...
invalidate_expensive_method_cache
..some code..
Got an idea? We could move further.
Not satisfied with default timeout?
caches :expensive_method, :timeout => 10.minutes
Want to cache an accessor’s value?
Caches.rb is for you. It automatically caches getter’s value and invalidates cache on writer invocation. No extra configuration required.
Expensive method has arguments?
No problem. Caches.rb caches invocations with arguments. So, if you have
def expensive_method(arg)
...
end
then Caches.rb will cache expensive_method(1) and expensive_method(2) separately. To invalidate cache for (1), just invalidate_expensive_method_cache(1). To invalidate all expensive_method caches, just invalidate_all_expensive_method_caches. Simple? Yes!
Other
Want to invalidate all caches within a class? invalidate_all_caches is for you.
Also you can invalidate caches with except some caches
invalidate_all_caches :except => :name
or
invalidate_all_caches :except => [:name, :name1]
Revised about 1 year ago by yrashk