Created
March 27, 2011 06:34
-
-
Save quamen/888988 to your computer and use it in GitHub Desktop.
Module that adds read through caching to ActiveResource
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_support/concern' | |
module CachedResource | |
extend ActiveSupport::Concern | |
included do | |
class << self | |
alias_method_chain :find, :read_through_cache | |
end | |
class_attribute :cache_for | |
end | |
module ClassMethods | |
def cache_expires_in | |
self.cache_for || 60 | |
end | |
def find_with_read_through_cache(*arguments) | |
key = cache_key(arguments) | |
result = Rails.cache.read(key).try(:dup) | |
unless result | |
result = find_without_read_through_cache(*arguments) | |
Rails.cache.write(key, result, :expires_in => self.cache_expires_in) | |
end | |
result | |
end | |
private | |
def cache_key(*arguments) | |
"#{name}/#{arguments.join('/')}".downcase | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice. Could you also include the last version you showed yesterday on RORO? The one with fallback to permanently cached values. Thanks, mate