Module: MemoizeMethod

Defined in:
lib/memoize_method.rb,
lib/memoize_method/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#cache(method) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/memoize_method.rb', line 4

def cache(method)
  cacheless_method = "cacheless_" + method.to_s
  recompute_method = "recompute_" + method.to_s
  cache_var = "@" + method.to_s + "_cache"
  alias_method cacheless_method, method
  define_method(method) { |*args|
    instance_eval(cache_var) ||
      instance_eval("#{cache_var} ||= send(cacheless_method, *args)")
  }

  define_method(recompute_method) { |*args|
    instance_eval("#{cache_var} = send(cacheless_method, *args)")
  }
end