Class: Perpetuity::Dereferencer
- Inherits:
-
Object
- Object
- Perpetuity::Dereferencer
- Defined in:
- lib/perpetuity/dereferencer.rb
Instance Attribute Summary collapse
-
#map ⇒ Object
readonly
Returns the value of attribute map.
-
#mapper_registry ⇒ Object
readonly
Returns the value of attribute mapper_registry.
Instance Method Summary collapse
- #[](reference) ⇒ Object
- #cache(objects) ⇒ Object
- #grouped(references) ⇒ Object
-
#initialize(mapper_registry, identity_map = IdentityMap.new) ⇒ Dereferencer
constructor
A new instance of Dereferencer.
- #load(references) ⇒ Object
- #objects(klass, ids) ⇒ Object
- #referenceable?(ref) ⇒ Boolean
Constructor Details
#initialize(mapper_registry, identity_map = IdentityMap.new) ⇒ Dereferencer
Returns a new instance of Dereferencer.
8 9 10 11 |
# File 'lib/perpetuity/dereferencer.rb', line 8 def initialize mapper_registry, identity_map=IdentityMap.new @map = identity_map @mapper_registry = mapper_registry end |
Instance Attribute Details
#map ⇒ Object (readonly)
Returns the value of attribute map.
6 7 8 |
# File 'lib/perpetuity/dereferencer.rb', line 6 def map @map end |
#mapper_registry ⇒ Object (readonly)
Returns the value of attribute mapper_registry.
6 7 8 |
# File 'lib/perpetuity/dereferencer.rb', line 6 def mapper_registry @mapper_registry end |
Instance Method Details
#[](reference) ⇒ Object
25 26 27 28 29 30 31 |
# File 'lib/perpetuity/dereferencer.rb', line 25 def [] reference if referenceable?(reference) map[reference.klass, reference.id] else reference end end |
#cache(objects) ⇒ Object
21 22 23 |
# File 'lib/perpetuity/dereferencer.rb', line 21 def cache objects objects.each { |object| map << object } end |
#grouped(references) ⇒ Object
33 34 35 |
# File 'lib/perpetuity/dereferencer.rb', line 33 def grouped references references.group_by(&:klass) end |
#load(references) ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/perpetuity/dereferencer.rb', line 13 def load references references = Array(references).flatten.select {|ref| referenceable?(ref) } cache grouped(references).map { |klass, refs| objects klass, refs.map(&:id) }.flatten end |
#objects(klass, ids) ⇒ Object
37 38 39 40 41 42 43 44 45 46 |
# File 'lib/perpetuity/dereferencer.rb', line 37 def objects klass, ids ids = ids.uniq if ids.one? mapper_registry.mapper_for(klass, identity_map: map).find(ids.first) elsif ids.none? [] else mapper_registry[klass].find(ids.uniq).to_a end end |
#referenceable?(ref) ⇒ Boolean
48 49 50 |
# File 'lib/perpetuity/dereferencer.rb', line 48 def referenceable? ref [:klass, :id].all? { |msg| ref.respond_to?(msg) } end |