class Shamu::Entities::StaticRepository
Implements an in-memory store of entities for static entities (rich enum types) offering standard read methods find
, lookup
and list
.
Attributes
entities[R]
missing_entity_class[R]
Public Class Methods
new( entities, missing_entity_class: nil )
click to toggle source
# File lib/shamu/entities/static_repository.rb, line 8 def initialize( entities, missing_entity_class: nil ) raise ArgumentError, :entities if entities.map( &:id ).count != entities.map( &:id ).uniq.count entities = entities.dup.freeze unless entities.frozen? @entities = entities @missing_entity_class = missing_entity_class || NullEntity.for( entities.first.class ) @lookup_cache = {} end
Public Instance Methods
find( id = :not_set ) { |: find_by( :id, id )| ... }
click to toggle source
Find an entity with the given id.
@return [Entity] the entity if found. @raise [Shamu::NotFoundError] if the entity could not be found.
# File lib/shamu/entities/static_repository.rb, line 35 def find( id = :not_set, &block ) raise ArgumentError, :id if id == :not_set && !block_given? value = block_given? ? yield : find_by( :id, id ) value || not_found! end
find_by( attribute, value )
click to toggle source
Find an entity with the given value on the named attribute.
@param [Object] value to look for. @param [Symbol] attribute to interrogate. @return [Entity] the entity if found. @raise [Shamu::NotFoundError] if the entity could not be found.
# File lib/shamu/entities/static_repository.rb, line 24 def find_by( attribute, value ) cache = attribute_cache( attribute ) cache.fetch value do cache[ value ] = find_by_attribute( attribute, value ) end end
list()
click to toggle source
@return [List<Entity>] all the entities in the repository.
# File lib/shamu/entities/static_repository.rb, line 59 def list List.new entities end
lookup( *ids )
click to toggle source
Lookup all the entities in the repository with the given ids. @param [Array<Integer>] ids @return [List<Entity>] the matching entities.
# File lib/shamu/entities/static_repository.rb, line 45 def lookup( *ids ) cache = attribute_cache( :id ) matching = ids.map do |id| entity = cache.fetch( id ) do entities.find { |e| e.id == id } end entity || missing_entity_class.new end List.new matching end
Private Instance Methods
attribute_cache( attribute )
click to toggle source
# File lib/shamu/entities/static_repository.rb, line 71 def attribute_cache( attribute ) @lookup_cache.fetch( attribute ) do @lookup_cache[ attribute ] = {} end end
find_by_attribute( attribute, value )
click to toggle source
# File lib/shamu/entities/static_repository.rb, line 77 def find_by_attribute( attribute, value ) entities.find { |e| e.send( attribute ) == value } || not_found! end
not_found!()
click to toggle source
# File lib/shamu/entities/static_repository.rb, line 67 def not_found! raise Shamu::NotFoundError end