Sha256: e15b6da1d2cf4f6ba7e4b110f0306041be040ebe9e19902076c50d581560b198

Contents?: true

Size: 1.36 KB

Versions: 1

Compression:

Stored size: 1.36 KB

Contents

module SequelMapper
  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

1 entries across 1 versions & 1 rubygems

Version Path
sequel_mapper-0.0.3 lib/sequel_mapper/association_loaders.rb