diff --git a/lib/cached_resource/caching.rb b/lib/cached_resource/caching.rb index a0eb457..b15023e 100644 --- a/lib/cached_resource/caching.rb +++ b/lib/cached_resource/caching.rb @@ -4,6 +4,8 @@ module CachedResource module Caching extend ActiveSupport::Concern + MAX_ARGUMENTS_CACHE_SIZE = 150 + included do class << self alias_method_chain :find, :cache @@ -112,10 +114,16 @@ def cache_clear # Generate the request cache key. def cache_key(*arguments) + "#{name.parameterize.gsub("-", "/")}/#{arguments_cache_key(*arguments)}".downcase.delete(' ') + end + + def arguments_cache_key(*arguments) arguments_string = arguments.join('/') - arguments_key = arguments_string.length > 150 ? Digest::SHA2.hexdigest(arguments_string) : arguments_string + arguments_string.length > MAX_ARGUMENTS_CACHE_SIZE ? hash_string(arguments_string) : arguments_string + end - "#{name.parameterize.gsub("-", "/")}/#{arguments_key}".downcase.delete(' ') + def hash_string(string) + Digest::SHA2.hexdigest(string) end # Make a full duplicate of an ActiveResource record. diff --git a/spec/cached_resource/caching_spec.rb b/spec/cached_resource/caching_spec.rb index b728e0e..0d9252d 100644 --- a/spec/cached_resource/caching_spec.rb +++ b/spec/cached_resource/caching_spec.rb @@ -56,6 +56,14 @@ class Thing < ActiveResource::Base Thing.cached_resource.cache.read('thing/1/{:from=>"path",:params=>{:foo=>"bar"}}').should == result end + it "should hash long parameters in cache key" do + params = [1, {long_params: "l" * Thing::MAX_ARGUMENTS_CACHE_SIZE }] + hash_params = Thing.send(:hash_string, params.join("/")) + + result = Thing.find(*params) + Thing.cached_resource.cache.read("thing/#{hash_params}").should == result + end + it "should empty the cache when clear_cache is called" do result = Thing.find(1) Thing.clear_cache @@ -510,4 +518,5 @@ class CustomCollection < ActiveResource::Collection; end new_result.name.should_not == old_result.name end end + end