Created
September 29, 2008 15:59
-
-
Save christianromney/13620 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Need to handle all of these.... | |
# [x] Reservation.find(123) | |
# [ ] Reservation.find(123,456,769) | |
# [ ] Reservation.find(:all) | |
# [ ] Reservation.find(:all, :conditions => ['foo = ?', 'bar']) | |
module Cacheable | |
@@store = nil | |
def self.store(backing_store) | |
@@store = backing_store | |
self | |
end | |
def cache | |
@@store | |
end | |
def self.find(*opts) | |
return super(*opts) unless opts.first.kind_of?(Integer) | |
key = cache_key_for(opts.first) | |
return cache[key] if cache.include? key | |
returning(super(*opts)) do |record| | |
cache[key] = record | |
end | |
end | |
protected | |
def self.cache_key_for(id) | |
prefix = ancestors.collect(&:name)[0..2].compact.join(':').downcase | |
"%s:%s" % [prefix, id.to_s] | |
end | |
end | |
CACHE = {} # this is defined by Rails.... | |
class Foo | |
include Cacheable::store(CACHE) | |
end | |
puts Foo.new.cache # yay! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment