Sha256: ca1155fdbbd07d1d6238e979a74d63bca520c9a4136a0005df70d94b933e23d9

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

require "sequel_mapper/dataset"

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

    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, &block)
      foreign_key_pair = {
        foreign_key => parent_record.fetch(key),
      }

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

    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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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