Skip to content

Instantly share code, notes, and snippets.

@quamen
Created March 27, 2011 06:34
Show Gist options
  • Save quamen/888988 to your computer and use it in GitHub Desktop.
Save quamen/888988 to your computer and use it in GitHub Desktop.
Module that adds read through caching to ActiveResource
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
@bobes
Copy link

bobes commented Apr 29, 2011

Very nice. Could you also include the last version you showed yesterday on RORO? The one with fallback to permanently cached values. Thanks, mate

@quamen
Copy link
Author

quamen commented Apr 29, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment