Sha256: 1c994db887a5a8f78dbe8c9462a709e72dd2b1c428b817d7e35728bf1d228580

Contents?: true

Size: 1.95 KB

Versions: 1

Compression:

Stored size: 1.95 KB

Contents

require File.expand_path(File.dirname(__FILE__) + '/resource')

module HashPersistent
  module Collection
    include HashPersistent::Resource

    def self.included(base)
      base.extend ClassMethods
    end
    
    module ClassMethods
      attr_accessor :basis
      
      def on_watched_store_save_event(store_for_collection, saved_object)
        raise "Cannot collect objects without a basis for the collection. Set :basis class attribute" unless @basis
        return unless saved_object.respond_to?(:basis) && saved_object.respond_to?(:key)
        
        collection_resource = store_for_collection.find(saved_object.send(:basis))
        unless collection_resource
          collection_resource = new
          collection_resource.store = store_for_collection
          collection_resource.key = saved_object.send(:basis)
        end
        
        collection_resource.collected_keys << saved_object.send(:key)
        collection_resource.collected_keys.uniq!
        collection_resource.save
      end

      def on_watched_store_delete_event(store_for_collection, deleted_object)
        raise "Cannot collect objects without a basis for the collection. Set :basis class attribute" unless @basis
        return unless deleted_object.respond_to?(:basis) && deleted_object.respond_to?(:key)
        
        collection_resource = store_for_collection.find(deleted_object.send(:basis))
        return unless collection_resource

        collection_resource.collected_keys.delete(deleted_object.send(:key))
        
        if collection_resource.collected_keys == []
          collection_resource.delete
        else
          collection_resource.save
        end
      end
    end
    
    def collected_keys
      @collected_keys ||= []
    end

    def collected_resources
      @collected_keys.collect do |key|
        resource = store.watching.find(key)
        raise "Collected key not found in watched store" unless resource
        resource
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
kissifer-hash-persistent-0.0.0 lib/hash-persistent/collection.rb