Skip to content

Instantly share code, notes, and snippets.

@quamen
Created April 29, 2011 02:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save quamen/947734 to your computer and use it in GitHub Desktop.
Save quamen/947734 to your computer and use it in GitHub Desktop.
Module that adds read through caching to ActiveResource with fallback to a permanent cache
require 'active_support/concern'
module CachedResource
extend ActiveSupport::Concern
included do
class << self
alias_method_chain :find, :cache
end
class_attribute :cache_for
end
module ClassMethods
def cache_expires_in
self.cache_for || 60
end
def find_with_cache(*arguments)
begin
key = cache_key(arguments)
perma_key = perma_cache_key(arguments)
find_with_read_through_cache(key, perma_key, *arguments)
rescue ActiveResource::ServerError, ActiveResource::ConnectionError, SocketError => e
Rails.cache.read(perma_key).try(:dup) || raise(e)
end
end
private
def find_with_read_through_cache(key, perma_key, *arguments)
result = Rails.cache.read(key).try(:dup)
unless result
result = find_without_cache(*arguments)
Rails.cache.write(key, result, :expires_in => self.cache_expires_in)
Rails.cache.write(perma_key, result)
end
result
end
def cache_key(*arguments)
"#{name}/#{arguments.join('/')}".downcase
end
def perma_cache_key(*arguments)
"perma/#{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