Class: CaRuby::Cache
- Inherits:
-
Object
- Object
- CaRuby::Cache
- Defined in:
- lib/caruby/database/cache.rb
Overview
Cache for objects held in memory and accessed by key.
Instance Attribute Summary collapse
-
#sticky ⇒ Object
readonly
The classes which are not cleared when #clear is called.
Instance Method Summary collapse
-
#[](item) ⇒ Object
If there is already a cached object with the same key as the given item, then this method returns that cached object.
-
#add(item) ⇒ Object
Adds the given item to this cache, unless one already exists.
-
#add!(item) ⇒ Object
Adds the given item to this cache.
-
#clear ⇒ Object
Clears the non-sticky class caches.
-
#initialize {|obj| ... } ⇒ Cache
constructor
A new instance of Cache.
Constructor Details
#initialize {|obj| ... } ⇒ Cache
Returns a new instance of Cache.
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/caruby/database/cache.rb', line 12 def initialize # Make the class => {object => {key => object}} hash. # The {object => {key => object}} hash is an Associative which converts the given # object to its key by calling the block given to this initializer. # The {{key => object} hash takes a key as an argument and returns the cached object. # If there is no cached object, then the object passed to the Associative is cached. @ckh = Jinx::LazyHash.new do kh = Hash.new # the obj => key associator assoc = Jinx::Associative.new do |obj| key = yield(obj) kh[key] if key end # the obj => key => value writer assoc.writer do |obj, value| key = yield(obj) raise ArgumentError.new("caRuby cannot cache object without a key: #{obj}") if key.nil? kh[key] = value end end @sticky = Set.new end |
Instance Attribute Details
#sticky ⇒ Object (readonly)
The classes which are not cleared when #clear is called.
8 9 10 |
# File 'lib/caruby/database/cache.rb', line 8 def sticky @sticky end |
Instance Method Details
#[](item) ⇒ Object
If there is already a cached object with the same key as the given item, then this method returns that cached object. Otherwise, this method caches the given item and returns that item.
42 43 44 |
# File 'lib/caruby/database/cache.rb', line 42 def [](item) @ckh[item.class][item] end |
#add(item) ⇒ Object
Adds the given item to this cache, unless one already exists.
50 51 52 |
# File 'lib/caruby/database/cache.rb', line 50 def add(item) @ckh[item.class][item] ||= item end |
#add!(item) ⇒ Object
Adds the given item to this cache. Overwrites an existing cache entry for the given item’s key, if one already exists.
58 59 60 |
# File 'lib/caruby/database/cache.rb', line 58 def add!(item) @ckh[item.class][item] = item end |
#clear ⇒ Object
Clears the non-sticky class caches.
63 64 65 66 67 68 69 |
# File 'lib/caruby/database/cache.rb', line 63 def clear if @sticky.empty? then @ckh.clear else @ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) } end end |