Sha256: fb21adc2908466d9a063721dfcc474d98af91891d8c85e7b963775262e7658e9

Contents?: true

Size: 1.31 KB

Versions: 1

Compression:

Stored size: 1.31 KB

Contents

module Terrestrial
  class RelationMapping
    def initialize(name:, namespace:, fields:, primary_key:, factory:, serializer:, associations:, subsets:)
      @name = name
      @namespace = namespace
      @fields = fields
      @primary_key = primary_key
      @factory = factory
      @serializer = serializer
      @associations = associations
      @subsets = subsets
    end

    attr_reader :name, :namespace, :fields, :primary_key, :factory, :serializer, :associations, :subsets

    def add_association(name, new_association)
      @associations = associations.merge(name => new_association)
    end

    def serialize(object, depth, foreign_keys = {})
      object_attributes = serializer.call(object)

      [
        record(object_attributes, depth, foreign_keys),
        extract_associations(object_attributes)
      ]
    end

    def record(attributes, depth, foreign_keys)
      UpsertedRecord.new(
        namespace,
        primary_key,
        select_mapped_fields(attributes).merge(foreign_keys),
        depth,
      )
    end

    def extract_associations(attributes)
      Hash[
        associations.map { |name, _association|
          [ name, attributes.fetch(name) ]
        }
      ]
    end

    def select_mapped_fields(attributes)
      attributes.select { |name, _value| fields.include?(name) }
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
terrestrial-0.1.1 lib/terrestrial/relation_mapping.rb