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 without the
all
flag.
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 {|item| ... } ⇒ Cache
constructor
A new instance of Cache.
Constructor Details
#initialize {|item| ... } ⇒ Cache
Returns a new instance of Cache.
12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/caruby/database/cache.rb', line 12 def initialize # Make the class => {key => item} hash. # The {key => item} hash takes an item as an argument and converts # it to the key by calling the block given to this initializer. @ckh = Jinx::LazyHash.new do Jinx::KeyTransformerHash.new do |obj| yield(obj) or Jinx.fail(ArgumentError, "The object to cache does not have a key: #{obj}") end end @sticky = Set.new end |
Instance Attribute Details
#sticky ⇒ Object (readonly)
The classes which are not cleared when #clear is called without the all
flag.
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.
31 32 33 |
# File 'lib/caruby/database/cache.rb', line 31 def [](item) @ckh[item.class][item] end |
#add(item) ⇒ Object
Adds the given item to this cache, unless one already exists.
39 40 41 |
# File 'lib/caruby/database/cache.rb', line 39 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.
47 48 49 |
# File 'lib/caruby/database/cache.rb', line 47 def add!(item) @ckh[item.class][item] = item end |
#clear ⇒ Object
Clears the non-sticky class caches.
52 53 54 55 56 57 58 |
# File 'lib/caruby/database/cache.rb', line 52 def clear if @sticky.empty? then @ckh.clear else @ckh.each { |klass, ch| ch.clear unless @sticky.include?(klass) } end end |