Return to Snippet

Revision: 9287
at October 28, 2008 17:46 by jnunemaker


Updated Code
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

Revision: 9286
at October 28, 2008 17:45 by jnunemaker


Initial Code
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

Initial URL
https://gist.github.com/20515/67021078e8c1a73260f94e3df29cf514e6334ccb

Initial Description


Initial Title
active record cache expensive methods

Initial Tags
rails

Initial Language
Ruby