Skip to content

Instantly share code, notes, and snippets.

@wesley6j
Forked from chrishawaii/acts_as_cacheable.rb
Created October 14, 2016 11:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wesley6j/c088ea82b157a0ba1fa0183937083c68 to your computer and use it in GitHub Desktop.
Save wesley6j/c088ea82b157a0ba1fa0183937083c68 to your computer and use it in GitHub Desktop.
module Acts
module Cacheable
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def acts_as_cacheable(key, options = {})
extend Acts::Cacheable::SingletonMethods
find(:all, options).each{|instance| cached_objects[instance.send(key).to_s] = instance}
end
end
module SingletonMethods
def [] (key)
cached_objects[key]
end
def cached(id)
cached_objects.each_value{|instance| return instance if instance.id == id}
end
def objects
cached_objects.values
end
private
def cached_objects
@all_cached_objects ||= Hash.new
end
end
end
end
class Person < ActiveRecord::Base
acts_as_cacheable :login, :conditions => {:admin => true}
end
class Unit < ActiveRecord::Base
acts_as_cacheable :key
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment