Sha256: 1ea7c51b7c041a6f0406a60b070e6d74ee8e8a58f5427a7901d94369c498d431

Contents?: true

Size: 1.53 KB

Versions: 2

Compression:

Stored size: 1.53 KB

Contents

require "forwardable"
require "terrestrial/inspection_string"

module Terrestrial
  class CollectionMutabilityProxy
    extend Forwardable
    include InspectionString
    include Enumerable

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

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

    def_delegators :collection, :where, :subset

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

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

    def to_ary
      to_a
    end

    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)
      force_load
      @added_nodes.push(node)
    end

    private

    def force_load
      to_a
    end

    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

2 entries across 2 versions & 1 rubygems

Version Path
terrestrial-0.5.0 lib/terrestrial/collection_mutability_proxy.rb
terrestrial-0.3.0 lib/terrestrial/collection_mutability_proxy.rb