public
Last active

Module that adds read through caching to ActiveResource with fallback to a permanent cache

  • Download Gist
cached_resource.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.