Sha256: 9069d4b585b563cbe7b0c367a0b3ef90c858368b7365a2c9286f4e4346a10ff7

Contents?: true

Size: 1.68 KB

Versions: 1

Compression:

Stored size: 1.68 KB

Contents

module HashPersistent
  module Collection
    
    def self.included(base)
      base.extend ClassMethods
      base.module_eval do
        include HashPersistent::Resource
      end
    end
    
    module ClassMethods
      attr_reader :resource_class
      
      def attach(resource_class, collection_basis)
        raise ArgumentError unless resource_class.included_modules.include?(HashPersistent::Resource)
        raise ArgumentError unless resource_class.instance_methods.include?(collection_basis.to_s)
        @collection_basis = collection_basis
        @resource_class = resource_class
        resource_class.on_save do |resource|
          collected_resource_saved(resource)
        end
        
        resource_class.on_delete do |resource|
          collected_resource_deleted(resource)
        end
      end
      
      def collected_resource_saved(resource)
        collection = find(resource.send(@collection_basis))
        unless collection
          collection = new
          collection.collected_keys = []
          collection.key = resource.send(@collection_basis)
        end
        collection.collected_keys << resource.key
        collection.collected_keys.uniq!
        collection.save
      end

      def collected_resource_deleted(resource)
        collection = find(resource.send(@collection_basis))
        collection.collected_keys.delete(resource.key)
        if collection.collected_keys.empty?
          collection.delete
        else
          collection.save
        end
      end
    end
    
    attr_accessor :collected_keys
    
    def collected_resources
      collected_keys.collect do |key|
        self.class.resource_class.send(:find, key)
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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