Class: Memoizer

Inherits:
Object show all
Defined in:
lib/standard/facets/memoizer.rb

Overview

Memoizer wraps objects to provide cached method calls.

class X
  def initialize ; @tick = 0 ; end
  def tick; @tick + 1; end
  def memo; @memo ||= Memoizer.new(self) ; end
end

x = X.new
x.tick       #=> 1
x.memo.tick  #=> 2
x.tick       #=> 3
x.memo.tick  #=> 2
x.tick       #=> 4
x.memo.tick  #=> 2

You can also use to cache collections of objects to gain code speed ups.

points = points.collect{|point| Memoizer.cache(point)}

After our algorithm has finished using points, we want to get rid of these Memoizer objects. That’s easy:

points = points.collect{|point| point.__self__ }

Or if you prefer (it is ever so slightly safer):

points = points.collect{|point| Memoizer.uncache(point)}

Memoizer is the work of Erik Veenstra

Copyright © 2006 Erik Veenstra

See javathink.blogspot.com/2008/09/what-is-memoizer-and-why-should-you.html

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ Memoizer

Returns a new instance of Memoizer.



41
42
43
44
# File 'lib/standard/facets/memoizer.rb', line 41

def initialize(object)
  @self  = object
  @cache = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object

Not thread-safe! Speed is important in caches… ;]



49
50
51
# File 'lib/standard/facets/memoizer.rb', line 49

def method_missing(method_name, *args, &block)
  @cache[[method_name, args, block]] ||= @self.__send__(method_name, *args, &block)
end

Class Method Details

.cache(object) ⇒ Object

def self; @self; end



55
56
57
# File 'lib/standard/facets/memoizer.rb', line 55

def self.cache(object)
  new(object)
end

.uncache(cached_object) ⇒ Object



59
60
61
# File 'lib/standard/facets/memoizer.rb', line 59

def self.uncache(cached_object)
  cached_object.instance_variable_get('@self')
end

Instance Method Details

#__self__Object



46
# File 'lib/standard/facets/memoizer.rb', line 46

def __self__ ; @self ; end