Class: Shamu::Entities::IdentityCache
- Inherits:
-
Object
- Object
- Shamu::Entities::IdentityCache
- Defined in:
- lib/shamu/entities/identity_cache.rb
Overview
Keeps a cache of Entity instances in memory for quick retrieval. Since entities are immutable, the cache
Instance Method Summary collapse
-
#add(key, entity) ⇒ entity
Add a new entity to the cache.
-
#fetch(key) ⇒ Entity
Fetch an entity with the given key.
-
#initialize(coercion = nil) {|key| ... } ⇒ IdentityCache
constructor
Provide a block to automatically coerce keys to a known type.
-
#invalidate(key) ⇒ Entity
Invalidate the cached entry for the Entity with the given
key
. -
#uncached_keys(keys) ⇒ Array
Filter the list of
keys
to those that haven't been cached yet.
Constructor Details
#initialize(coercion = nil) {|key| ... } ⇒ IdentityCache
Provide a block to automatically coerce keys to a known type. For example converting numeric strings ("123") to Integer values.
16 17 18 19 |
# File 'lib/shamu/entities/identity_cache.rb', line 16 def initialize( coercion = nil, &coercion_block ) @cache = {} @coercion = block_given? ? coercion_block : ( coercion && coercion.to_proc ) end |
Instance Method Details
#add(key, entity) ⇒ entity
Add a new entity to the cache.
42 43 44 |
# File 'lib/shamu/entities/identity_cache.rb', line 42 def add( key, entity ) cache[ coerce_key( key ) ] = entity end |
#fetch(key) ⇒ Entity
Fetch an entity with the given key.
24 25 26 |
# File 'lib/shamu/entities/identity_cache.rb', line 24 def fetch( key ) cache.fetch( coerce_key( key ), nil ) end |
#invalidate(key) ⇒ Entity
Invalidate the cached entry for the Entity with the given key
.
49 50 51 |
# File 'lib/shamu/entities/identity_cache.rb', line 49 def invalidate( key ) cache.delete( key ) end |
#uncached_keys(keys) ⇒ Array
Filter the list of keys
to those that haven't been cached yet.
32 33 34 35 36 |
# File 'lib/shamu/entities/identity_cache.rb', line 32 def uncached_keys( keys ) uncached = Array( keys ).map { |k| coerce_key( k ) } uncached.reject! { |k| cache.key?( k ) } uncached end |