Skip to content

Instantly share code, notes, and snippets.

@christos
Forked from technoweenie/gist:20515
Created October 28, 2008 22:06
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 christos/20534 to your computer and use it in GitHub Desktop.
Save christos/20534 to your computer and use it in GitHub Desktop.
class ActiveRecord::Base
@@cache_store = nil
def self.cache_store
@@cache_store ||= ActionController::Base.cache_store
end
def self.caches(method_name, key = nil, options = {}, &block)
if key.is_a?(Hash)
options = key
key = nil
end
define_method "cached_#{method_name}" do
key = instance_eval(&block) if block
self.class.cache_store.fetch("#{method_name}:#{key}", options) { send(method_name) }
end
end
end
class MyModel < ActiveRecord::Base
caches(:expensive_query, :expires_in => 15.minutes) { "#{id}:#{id.updated_at.to_i}" }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment