Class: SequelMapper::AssociationLoaders::OneToMany

Inherits:
Object
  • Object
show all
Defined in:
lib/sequel_mapper/association_loaders.rb

Instance Method Summary collapse

Constructor Details

#initialize(type:, mapping_name:, foreign_key:, key:, proxy_factory:) ⇒ OneToMany

Returns a new instance of OneToMany.



4
5
6
7
8
9
10
11
# File 'lib/sequel_mapper/association_loaders.rb', line 4

def initialize(type:, mapping_name:, foreign_key:, key:, proxy_factory:)
  @type = type
  @mapping_name = mapping_name
  @foreign_key = foreign_key
  @key = key
  @proxy_factory = proxy_factory
  @eager_loads = {}
end

Instance Method Details

#call(mappings, record, &object_pipeline) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/sequel_mapper/association_loaders.rb', line 25

def call(mappings, record, &object_pipeline)
  mapping = mappings.fetch(mapping_name)

  proxy_factory.call(
    query: query(mapping, record),
    loader: object_pipeline.call(mapping),
    association_loader: self,
  )
end

#eager_load(dataset, association_name) ⇒ Object



46
47
48
49
# File 'lib/sequel_mapper/association_loaders.rb', line 46

def eager_load(dataset, association_name)
  datastore[mapping.namespace]
    .where(foreign_key => dataset.select(key))
end

#fetch(*args, &block) ⇒ Object



16
17
18
19
20
21
22
23
# File 'lib/sequel_mapper/association_loaders.rb', line 16

def fetch(*args, &block)
  {
    key: key,
    foreign_key: foreign_key,
    type: type,
    mapping_name: mapping_name,
  }.fetch(*args, &block)
end

#query(mapping, record) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/sequel_mapper/association_loaders.rb', line 35

def query(mapping, record)
  foreign_key_value = record.fetch(key)

  ->(datastore) {
    @eager_loads.fetch(record) {
      datastore[mapping.namespace]
        .where(foreign_key => foreign_key_value)
    }
  }
end