Sha256: 425e254e921d3be4a243cee59406758d26117e2366104d811f57b47ee6958c24

Contents?: true

Size: 1.36 KB

Versions: 2

Compression:

Stored size: 1.36 KB

Contents

module Terrestrial
  module AssociationLoaders
    class OneToMany
      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

      attr_reader :type, :mapping_name, :foreign_key, :key, :proxy_factory
      private     :type, :mapping_name, :foreign_key, :key, :proxy_factory

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

      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

      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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
terrestrial-0.3.0 lib/terrestrial/association_loaders.rb
terrestrial-0.1.1 lib/terrestrial/association_loaders.rb