Module: Memoizable
- Included in:
- Rash
- Defined in:
- lib/hoodie/memoizable.rb
Overview
Memoization is an optimization that saves the return value of a method so it doesn’t need to be re-computed every time that method is called.
Instance Method Summary collapse
-
#memoize(methods, cache = nil) ⇒ undefined
Create a new memoized method.
Instance Method Details
#memoize(methods, cache = nil) ⇒ undefined
Create a new memoized method. To use, extend class with Memoizable, then, in initialize, call memoize
31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/hoodie/memoizable.rb', line 31 def memoize(methods, cache = nil) cache ||= Stash.new methods.each do |name| uncached_name = "#{name}_uncached".to_sym singleton_class.class_eval do alias_method uncached_name, name define_method(name) do |*a, &b| cache.cache(name) { send uncached_name, *a, &b } end end end end |