Sha256: a0d588064fb784147b60084ef93e84cc782f303d6015557b82595c0e830a5df3

Contents?: true

Size: 1.78 KB

Versions: 1

Compression:

Stored size: 1.78 KB

Contents

module Cash
  module WriteThrough
    DEFAULT_TTL = 12.hours.to_i

    def self.included(active_record_class)
      active_record_class.class_eval do
        include InstanceMethods
        extend ClassMethods
      end
    end

    module InstanceMethods
      def self.included(active_record_class)
        active_record_class.class_eval do
          after_create :add_to_caches
          after_update :update_caches
          after_destroy :remove_from_caches
        end
      end

      def add_to_caches
        InstanceMethods.unfold(self.class, :add_to_caches, self)
      end

      def update_caches
        InstanceMethods.unfold(self.class, :update_caches, self)
      end

      def remove_from_caches
        return if new_record?
        InstanceMethods.unfold(self.class, :remove_from_caches, self)
      end

      def expire_caches
        InstanceMethods.unfold(self.class, :expire_caches, self)
      end

      def shallow_clone
        self.class.send(:instantiate, instance_variable_get(:@attributes))
      end

      private
      def self.unfold(klass, operation, object)
        while klass < ActiveRecord::Base && klass.ancestors.include?(WriteThrough)
          klass.send(operation, object)
          klass = klass.superclass
        end
      end
    end

    module ClassMethods
      def add_to_caches(object)
        indices.each { |index| index.add(object) } if cacheable?
        true
      end

      def update_caches(object)
        indices.each { |index| index.update(object) } if cacheable?
        true
      end

      def remove_from_caches(object)
        indices.each { |index| index.remove(object) } if cacheable?
        true
      end

      def expire_caches(object)
        indices.each { |index| index.delete(object) } if cacheable?
        true
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ngmoco-cache-money-0.2.24.2 lib/cash/write_through.rb