Cache Decorator

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

Jake McArthur wrote:

use a bunch of those extra variables that make code so much harder to
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

What do you feel are the pros and cons vs. memoize?

What do you feel are the pros and cons vs. memoize?

I haven’t really done a benchmark to compare them directly, but
memoization does not allow a cache to expire or invalidate, which
makes it less useful for many cases. On the other hand, memoize
allows you to cache to a file instead of just memory. Memoize is also
still a bit cleaner right now as far as usage goes, but I plan on
modifying and extending Cache Decorator pretty soon.

  • Jake McArthur

I have been working on my own Cache called Memoize, see it here
http://www.eachmapinject.com/treasure_chest/index.cgi/browser/memoize
I have not put it on to RubyForge just yet, I will do so soon.

j`ey
http://www.eachmapinject.com