Class: Shamu::Entities::StaticRepository
- Inherits:
-
Object
- Object
- Shamu::Entities::StaticRepository
- Defined in:
- lib/shamu/entities/static_repository.rb
Overview
Implements an in-memory store of entities for static entities (rich enum types) offering standard read methods #find, #lookup and #list.
Instance Method Summary collapse
-
#find(id = :not_set, &block) ⇒ Entity
Find an entity with the given id.
-
#find_by(attribute, value) ⇒ Entity
Find an entity with the given value on the named attribute.
-
#initialize(entities, missing_entity_class: nil) ⇒ StaticRepository
constructor
A new instance of StaticRepository.
-
#list ⇒ List<Entity>
All the entities in the repository.
-
#lookup(*ids) ⇒ List<Entity>
Lookup all the entities in the repository with the given ids.
Constructor Details
#initialize(entities, missing_entity_class: nil) ⇒ StaticRepository
Returns a new instance of StaticRepository.
8 9 10 11 12 13 14 15 16 |
# 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 |
Instance Method Details
#find(id = :not_set, &block) ⇒ Entity
Find an entity with the given id.
35 36 37 38 39 40 |
# 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) ⇒ Entity
Find an entity with the given value on the named attribute.
24 25 26 27 28 29 |
# 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 ⇒ List<Entity>
Returns all the entities in the repository.
59 60 61 |
# File 'lib/shamu/entities/static_repository.rb', line 59 def list List.new entities end |
#lookup(*ids) ⇒ List<Entity>
Lookup all the entities in the repository with the given ids.
45 46 47 48 49 50 51 52 53 54 55 56 |
# 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 |