Sha256: f835e3ab00302622dcafab9a9db2429ac2d0d0a30b892091dca1a991939d2cf6

Contents?: true

Size: 1.34 KB

Versions: 1

Compression:

Stored size: 1.34 KB

Contents

require "sequel_mapper/short_inspection_string"

module SequelMapper
  class QueryableLazyDatasetLoader
    include ShortInspectionString
    include Enumerable

    def initialize(database_enum, loader, queries)
      @database_enum = database_enum
      @loader = loader
      @queries = queries
      @loaded = false
    end

    attr_reader :database_enum, :loader, :queries
    private     :database_enum, :loader, :queries

    def where(criteria)
      self.class.new(database_enum.where(criteria), loader, queries)
    end

    def subset(name, *params)
      self.class.new(
        queries.execute(database_enum, name, *params),
        loader,
        queries,
      )
    end

    def each(&block)
      enum.each(&block)
    end

    def each_loaded(&block)
      loaded_objects.each(&block)
    end

    private

    def enum
      @enum ||= Enumerator.new { |yielder|
        loaded_objects.each do |obj|
          yielder.yield(obj)
        end

        loop do
          object_enum.next.tap { |obj|
            loaded_objects.push(obj)
            yielder.yield(obj)
          }
        end
      }
    end

    def object_enum
      @object_enum ||= database_enum.lazy.map(&loader)
    end

    def loaded_objects
      @loaded_objects ||= []
    end

    def inspectable_properties
      [
        :database_enum,
        :loaded,
      ]
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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