Sha256: b24c6d63a80dfab6c1abc3990fa3c38022009e74490befd5ae275ff4005f2465

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

module HashPersistent
  module Collection
    
    def self.included(base)
      base.extend ClassMethods
      base.module_eval do
        include HashPersistent::Resource
      end
    end
    
    module ClassMethods
      def attach(resource_class, collection_basis)
        raise ArgumentError unless resource_class.included_modules.include?(HashPersistent::Resource)
        raise ArgumentError unless resource_class.new.respond_to?(collection_basis)
        @collection_basis = collection_basis
        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
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

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