Class: SequelMapper::GraphSerializer

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

Instance Method Summary collapse

Constructor Details

#initialize(mappings:) ⇒ GraphSerializer

Returns a new instance of GraphSerializer.



6
7
8
9
10
# File 'lib/sequel_mapper/graph_serializer.rb', line 6

def initialize(mappings:)
  @mappings = mappings
  @count = 0
  @encountered_records = Set.new
end

Instance Method Details

#call(mapping_name, object, foreign_key = {}) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/sequel_mapper/graph_serializer.rb', line 15

def call(mapping_name, object, foreign_key = {})
  # TODO may need some attention :)
  mapping = mappings.fetch(mapping_name)
  serializer = mapping.serializer
  namespace = mapping.namespace
  primary_key = mapping.primary_key
  fields = mapping.fields
  associations_map = mapping.associations

  serialized_record = serializer.call(object)

  current_record = UpsertedRecord.new(
    namespace,
    record_identity(primary_key, serialized_record),
    serialized_record
      .select { |k, _v| fields.include?(k) }
      .merge(foreign_key)
  )

  if encountered_records.include?(current_record.identity)
    return [current_record]
  else
    encountered_records.add(current_record.identity)
  end

  [current_record] + associations_map
    .map { |name, association|
      [serialized_record.fetch(name), association]
    }
    .map { |collection, association|
      [nodes(collection), deleted_nodes(collection), association]
    }
    .map { |nodes, deleted_nodes, association|
      assoc_mapping = mappings.fetch(association.mapping_name)

      association.dump(current_record, nodes) { |assoc_mapping_name, assoc_object, foreign_key|
        call(assoc_mapping_name, assoc_object, foreign_key)
      } +
      association.delete(current_record, deleted_nodes) { |assoc_mapping_name, assoc_object, foreign_key|
        delete(assoc_mapping_name, assoc_object, foreign_key)
      }
    }
    .flatten(1)
end