Sha256: 9fe5d882398cc59bfcb2c906aaec2877c62e9a4c55bf5c8c98e88446d8d4b73c

Contents?: true

Size: 1.58 KB

Versions: 1

Compression:

Stored size: 1.58 KB

Contents

require "terrestrial/dataset"

module Terrestrial
  class OneToManyAssociation
    def initialize(mapping_name:, foreign_key:, key:, order:, proxy_factory:)
      @mapping_name = mapping_name
      @foreign_key = foreign_key
      @key = key
      @order = order
      @proxy_factory = proxy_factory
    end

    def mapping_names
      [mapping_name]
    end

    def outgoing_foreign_keys
      [foreign_key]
    end

    def local_foreign_keys
      []
    end

    attr_reader :mapping_name

    attr_reader :foreign_key, :key, :order, :proxy_factory
    private     :foreign_key, :key, :order, :proxy_factory

    def build_proxy(data_superset:, loader:, record:)
     proxy_factory.call(
        query: build_query(data_superset, record),
        loader: loader,
        mapping_name: mapping_name,
      )
    end

    def dump(parent_record, collection, depth, &block)
      foreign_key_pair = {
        foreign_key => parent_record.fetch(key),
      }

      collection.flat_map { |associated_object|
        block.call(mapping_name, associated_object, foreign_key_pair, depth + depth_modifier)
      }
    end
    alias_method :delete, :dump

    def extract_foreign_key(_record)
      {}
    end

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

    def build_query((superset), record)
      order.apply(
        superset.where(foreign_key => record.fetch(key))
      )
    end

    private

    def depth_modifier
      +1
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
terrestrial-0.5.0 lib/terrestrial/one_to_many_association.rb