From: Brian Candler Date: 2008-12-03T06:11:01+09:00 Subject: Re: dynamic programming Frank Tao wrote: > # I have a class Adam > # I want to modify the method("m_a") so that it will return the cached > result > # If no cached result is available, then return the original result > # I want to create a class method(AKA: macro) to make it DRY You might want to look at the 'memoize' method in ActiveRecord trunk. > # So far, I have issues like > # 1) dynmically define class variable I suggest: don't use a class variable :-) An instance variable of the class would be fine. But personally I wouldn't keep the memoized values in the class; I'd keep them in the instances themselves. > # 2) failed to include a module inside a method of a class Look at Module.included for this, as shown below. There are probably cleaner and/or more efficient ways than the following, but it demonstrates the principle. module Cache def self.included(base) base.extend ClassMethods end module ClassMethods def caching_method(m) name = "orig_#{m}" var = "@__#{m}" alias_method name, m define_method(m) { |*args| return instance_variable_get(var) if instance_variable_defined?(var) instance_variable_set(var, send(name,*args)) } end end end class Adam include Cache def foo rand(100) end caching_method :foo end a = Adam.new p a.foo p a.foo p a.foo Beware of what you really want here though. If foo takes arguments, do you want foo(1) and foo(2) to be able to return different values? Do you want them both to be cached? If so, I leave that as an exercise for you. -- Posted via http://www.ruby-forum.com/.