CacheDecorator
CacheDecorator wrap objects to provide cached versions of method calls.
Usage
class X def initialize ; @tick = 0 ; end def tick; @tick + 1; end def cached; @cache ||= CacheDecorator.new(self) ; end end x = X.new x.tick #=> 1 x.cached.tick #=> 2 x.tick #=> 3 x.cached.tick #=> 2 x.tick #=> 4 x.cached.tick #=> 2
You can also use to cache a collections of objects to gain code speed ups.
points = points.collect{|point| Cache.cache(point)}
After our algorithm has finished using points, we want to get rid of these Cache objects. That‘s easy:
points = points.collect{|point| point.self }
Or if you prefer (it is ever so slightly safer):
points = points.collect{|point| Cache.uncache(point)}
Methods
cache
method_missing
new
self
uncache
Public Class methods
[ + ]
# File lib/more/facets/cachedecorator.rb, line 104 def self.cache(object) Cache.new(object) end
[ + ]
# File lib/more/facets/cachedecorator.rb, line 92 def initialize(object) @self = object @cache = {} end
[ + ]
# File lib/more/facets/cachedecorator.rb, line 108 def self.uncache(cached_object) cached_object.self end
Public Instance methods
[ + ]
# File lib/more/facets/cachedecorator.rb, line 97 def method_missing(method_name, *args, &block) # Not thread-safe! Speed is important in caches... ;] @cache[[method_name, args, block]] ||= @self.__send__(method_name, *args, &block) end
[ + ]
# File lib/more/facets/cachedecorator.rb, line 102 def self; @self; end