Sha256: b2046ccbd97155e311ade99441386a8c57b03bfdf58516da9cd472e05a3da0bc

Contents?: true

Size: 1.26 KB

Versions: 2

Compression:

Stored size: 1.26 KB

Contents

module Cacheable
  module AttributeCache
    def with_attribute(*attributes)
      self.cached_indices ||= {}
      self.cached_indices = self.cached_indices.merge(attributes.each_with_object({}) {
        |attribute, indices| indices[attribute] = {}
      })

      class_eval do
        after_commit :expire_attribute_cache, :on => :update
        after_commit :expire_all_attribute_cache, :on => :update
      end

      attributes.each do |attribute|
        define_singleton_method("find_cached_by_#{attribute}") do |value|
          self.cached_indices["#{attribute}"] ||= []
          self.cached_indices["#{attribute}"] << value
          Cacheable.fetch(attribute_cache_key("#{attribute}", value)) do
            self.send("find_by_#{attribute}", value)
          end
        end

        define_singleton_method("find_cached_all_by_#{attribute}") do |value|
          self.cached_indices["#{attribute}"] ||= []
          self.cached_indices["#{attribute}"] << value
          Cacheable.fetch(all_attribute_cache_key("#{attribute}", value)) do
            if Cacheable.rails4?
              self.where("#{attribute}" => value).load
            else
              self.send("find_all_by_#{attribute}", value)
            end
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
simple_cacheable-1.5.1 lib/cacheable/types/attribute_cache.rb
simple_cacheable-1.5.0 lib/cacheable/types/attribute_cache.rb