Posted By

jnunemaker on 10/28/08


Tagged

rails active record caching


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

inkdeep
webstic


active record cache expensive methods


 / Published in: Ruby
 

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

  1. class ActiveRecord::Base
  2. @@cache_store = nil
  3. def self.cache_store
  4. @@cache_store ||= ActionController::Base.cache_store
  5. end
  6.  
  7. def self.caches(method_name, key = nil, options = {}, &block)
  8. if key.is_a?(Hash)
  9. options = key
  10. key = nil
  11. end
  12. define_method "cached_#{method_name}" do
  13. key = instance_eval(&block) if block
  14. self.class.cache_store.fetch("#{method_name}:#{key}", options) { send(method_name) }
  15. end
  16. end
  17. end
  18.  
  19. class MyModel < ActiveRecord::Base
  20. caches(:expensive_query, :expires_in => 15.minutes) { "#{id}:#{id.updated_at.to_i}" }
  21. end

Report this snippet  

You need to login to post a comment.