Sha256: 348db2842074dffa8b3f1e3b407ce6d18b9a590d6ffee5bbe2bc0338df57197e

Contents?: true

Size: 1.45 KB

Versions: 3

Compression:

Stored size: 1.45 KB

Contents

module HashPersistent
  module Resource
    def self.included(base)
      base.extend ClassMethods
      base.module_eval do
        @store = {}
        @prefix = ""
      end
    end
    
    module ClassMethods
      def persist_to(store, prefix)
        raise ArgumentError unless store.respond_to?(:has_key?) and prefix.respond_to?(:to_s)
        @store = store
        @prefix = prefix
      end
    
      def find(key)
        @store[@prefix + key]
      end
      
      def on_save(&block)
        if block
          @on_save = block
        else
          @on_save
        end
      end

      def on_delete(&block)
        if block
          @on_delete = block
        else
          @on_delete
        end
      end
    
      attr_reader :store, :prefix
    end

    attr_accessor :key

    def prefix_key
      self.class.prefix + key
    end

    def save
      raise RuntimeError unless key
      self.class.store[prefix_key] = self
      self.class.on_save.call(self) if self.class.on_save
    end

    def delete
      raise RuntimeError unless key
      return unless self.class.store.has_key?(prefix_key)
      # TODO concurrency here, the store's delete call should cope, but we don't want the callback if something else got in first?
      # Alternative: ensure that callback handles this case, which is true of HashPersistent::Collection
      self.class.store.delete(prefix_key)
      self.class.on_delete.call(self) if self.class.on_delete
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
kissifer-hash-persistent-0.2.0 lib/hash-persistent/resource.rb
kissifer-hash-persistent-0.2.1 lib/hash-persistent/resource.rb
kissifer-hash-persistent-0.2.2 lib/hash-persistent/resource.rb