module SimpleModelCache::ClassMethods

Public Instance Methods

cache_fields(*fields) click to toggle source
# File lib/simple_model_cache.rb, line 16
def cache_fields(*fields)
        @cached_fields = [:id]
        @cached_fields += fields
        define_finder_methods
end
find(*id_params) click to toggle source
Calls superclass method
# File lib/simple_model_cache.rb, line 22
def find(*id_params)
        ids = id_params.compact
        from_cache = ids.count == 1 ? find_one(ids.first) : find_many(ids) 
        if from_cache.blank?
                super
        else
                from_cache
        end
end

Private Instance Methods

cache_by_each_field(hash, item) click to toggle source
# File lib/simple_model_cache.rb, line 69
def cache_by_each_field(hash, item)
        @cached_fields.each do |field|
                key = cache_key(field, item.send(field).to_s)
                hash[key] = item
        end
end
cache_key(field, value) click to toggle source
# File lib/simple_model_cache.rb, line 76
def cache_key(field, value)
        "#{self.name}#{field}:#{value}"
end
define_finder_methods() click to toggle source
Calls superclass method
# File lib/simple_model_cache.rb, line 51
def define_finder_methods
        @cached_fields.each do |field|
                finder_method = "find_by_#{field}"
                define_singleton_method(finder_method) do |arg|
                        key = cache_key(field, arg)
                        storage[key] || super(arg)
                end 
        end
end
find_many(ids) click to toggle source
# File lib/simple_model_cache.rb, line 46
def find_many(ids)
        cache_keys = ids.map {|id| cache_key(:id, id)}
        storage.values_at(*cache_keys)
end
find_one(id) click to toggle source
# File lib/simple_model_cache.rb, line 42
def find_one(id)
        storage[cache_key(:id, id)]
end
load_all() click to toggle source
# File lib/simple_model_cache.rb, line 61
def load_all
        hash = {}
        all.each do |item|
                cache_by_each_field(hash, item)
        end
        hash
end
reset_storage!() click to toggle source
# File lib/simple_model_cache.rb, line 38
def reset_storage!
        @@storage = nil
end
storage() click to toggle source
# File lib/simple_model_cache.rb, line 34
def storage
        @@storage ||= load_all
end