Skip to content

Instantly share code, notes, and snippets.

@christianromney
Created September 29, 2008 15:59
Show Gist options
  • Save christianromney/13620 to your computer and use it in GitHub Desktop.
Save christianromney/13620 to your computer and use it in GitHub Desktop.
# 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