Class: Cache
Overview
Cache
Cache objects are a kind of “delegator-with-cache”.
Usage
class X
def initialize ; @tick = 0 ; end
def tick; @tick + 1; end
def cached; @cache ||= Cache.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)}
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(object) ⇒ Cache
constructor
A new instance of Cache.
- #method_missing(method_name, *args, &block) ⇒ Object
- #self ⇒ Object
Constructor Details
#initialize(object) ⇒ Cache
Returns a new instance of Cache.
70 71 72 73 |
# File 'lib/more/facets/cachedelegator.rb', line 70 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
75 76 77 78 |
# File 'lib/more/facets/cachedelegator.rb', line 75 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 |
Class Method Details
.cache(object) ⇒ Object
82 83 84 |
# File 'lib/more/facets/cachedelegator.rb', line 82 def self.cache(object) Cache.new(object) end |
.uncache(cached_object) ⇒ Object
86 87 88 |
# File 'lib/more/facets/cachedelegator.rb', line 86 def self.uncache(cached_object) cached_object.self end |
Instance Method Details
#self ⇒ Object
80 |
# File 'lib/more/facets/cachedelegator.rb', line 80 def self; @self; end |