Class: Terrestrial::ManyToOneAssociation

Inherits:
Object
  • Object
show all
Defined in:
lib/terrestrial/many_to_one_association.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mapping_name:, foreign_key:, key:, proxy_factory:) ⇒ ManyToOneAssociation

Returns a new instance of ManyToOneAssociation.



5
6
7
8
9
10
# File 'lib/terrestrial/many_to_one_association.rb', line 5

def initialize(mapping_name:, foreign_key:, key:, proxy_factory:)
  @mapping_name = mapping_name
  @foreign_key = foreign_key
  @key = key
  @proxy_factory = proxy_factory
end

Instance Attribute Details

#mapping_nameObject (readonly)

Returns the value of attribute mapping_name.



24
25
26
# File 'lib/terrestrial/many_to_one_association.rb', line 24

def mapping_name
  @mapping_name
end

Instance Method Details

#build_proxy(data_superset:, loader:, record:) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/terrestrial/many_to_one_association.rb', line 29

def build_proxy(data_superset:, loader:, record:)
  foreign_key_nil?(record) ? nil : proxy_factory.call(
      query: build_query(data_superset, record),
      loader: loader,
      preloaded_data: {
        key => foreign_key_value(record),
      },
    )
end

#build_query(superset, record) ⇒ Object



47
48
49
# File 'lib/terrestrial/many_to_one_association.rb', line 47

def build_query((superset), record)
  superset.where(key => foreign_key_value(record))
end

#dump(parent_record, collection, depth, &block) ⇒ Object Also known as: delete



51
52
53
54
55
56
57
# File 'lib/terrestrial/many_to_one_association.rb', line 51

def dump(parent_record, collection, depth, &block)
  collection
    .reject(&:nil?)
    .flat_map { |object|
      block.call(mapping_name, object, _foreign_key_does_not_go_here = {}, depth + depth_modifier)
    }
end

#eager_superset(superset, associated_dataset) ⇒ Object



39
40
41
42
43
44
45
# File 'lib/terrestrial/many_to_one_association.rb', line 39

def eager_superset((superset), (associated_dataset))
  [
    Dataset.new(
      superset.where(key => associated_dataset.select(foreign_key)).to_a
    )
  ]
end

#extract_foreign_key(record) ⇒ Object



60
61
62
63
64
# File 'lib/terrestrial/many_to_one_association.rb', line 60

def extract_foreign_key(record)
  {
    foreign_key => record.fetch(key),
  }.reject { |_k, v| v.nil? }
end

#local_foreign_keysObject



20
21
22
# File 'lib/terrestrial/many_to_one_association.rb', line 20

def local_foreign_keys
  [foreign_key]
end

#mapping_namesObject



12
13
14
# File 'lib/terrestrial/many_to_one_association.rb', line 12

def mapping_names
  [mapping_name]
end

#outgoing_foreign_keysObject



16
17
18
# File 'lib/terrestrial/many_to_one_association.rb', line 16

def outgoing_foreign_keys
  []
end