Class: Shamu::Entities::IdentityCache

Inherits:
Object
  • Object
show all
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

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.

Parameters:

  • coercion (Symbol) (defaults to: nil)

    method to call on keys instead of providing a block.

Yields:

  • (key)

Yield Parameters:

  • key (Object)

    to coerce

Yield Returns:

  • (Object)

    the coerced value of the key.



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.

Parameters:

  • key (Object)

    of the entity. Typically the Entity#id.

  • entity (Entity)

    to cache

Returns:

  • (entity)


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.

Parameters:

  • key (Object)

    of the entity. Typically the Entity#id.

Returns:

  • (Entity)

    the entity if found, otherwise nil.



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.

Parameters:

  • key (Object)

    of the entity. Typically the Entity#id.

Returns:

  • (Entity)

    the entity that was at the given key if present.



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.

Parameters:

Returns:

  • (Array)

    the uncached keys.



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