This isn’t really anything that hasn’t been done before, but I have
yet to see some public Ruby code that provides a nice, easy way to
cache the results of methods with this much flexibility and
convenience. Simply wrap an object in a CacheDecorator object, and
cache away. Method results are stored for each set of arguments that
are passed to it. You can choose which methods of the object are
cached, invalidate caches manually, stop caching methods, set whether
the caches expire after some amount of time, and even set some
methods to invalidate the caches of other methods of the same object.
We cache things pretty often when things are too slow, but let’s not
use a bunch of those extra variables that make code so much harder to
read. Simple example:
obj = CacheDecorator.new(obj)
obj.cache :foo # caches foo
obj.cache :bar, 5 # caches bar with an expiry time of 5 seconds
loop do
puts obj.foo # stays the same the whole time
puts obj.bar # changes every five seconds
end
This is actually something I worked on a long time ago. I just didn’t
ever announce it. Also, it’s been a long time since it was updated,
but I intend to add a few more features/conveniences to it pretty soon.
Get it here: http://rubyforge.org/projects/cache-decorator/
- Jake McArthur