active record cache expensive methods


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.