Sha256: 3549cea3df81f12d00de642cf86fb0ce7fd8f50cac258cfa063bf936bb500977

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

require "forwardable"
require "sequel_mapper/short_inspection_string"

module SequelMapper
  class CollectionMutabilityProxy
    include ShortInspectionString

    def initialize(collection)
      @collection = collection
      @added_nodes = []
      @deleted_nodes = []
    end

    attr_reader :collection, :deleted_nodes, :added_nodes
    private     :collection, :deleted_nodes, :added_nodes

    extend Forwardable
    def_delegators :collection, :where, :subset

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

    def each_deleted(&block)
      @deleted_nodes.each(&block)
    end

    include Enumerable
    def each(&block)
      if block
        enum.each(&block)
        self
      else
        enum
      end
    end

    def delete(node)
      @deleted_nodes.push(node)
      self
    end

    def push(node)
      @added_nodes.push(node)
    end

    private

    def loaded_enum
      Enumerator.new do |yielder|
        collection.each_loaded do |element|
          yielder.yield(element) unless deleted?(element)
        end

        added_nodes.each do |node|
          yielder.yield(node)
        end
      end
    end

    def enum
      Enumerator.new do |yielder|
        collection.each do |element|
          yielder.yield(element) unless deleted?(element)
        end

        added_nodes.each do |node|
          yielder.yield(node)
        end
      end
    end

    def deleted?(node)
      @deleted_nodes.include?(node)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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