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

Instance Method Details

#memoize(methods, cache = nil) ⇒ undefined

Create a new memoized method. To use, extend class with Memoizable, then, in initialize, call memoize

Returns:

  • (undefined)


32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/hoodie/memoizable.rb', line 32

def memoize(methods, cache = nil)
  cache ||= Stash.new
  methods.each do |name|
    uncached_name = "#{name}_uncached".to_sym
    (class << self; self; end).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