From 64e4b4a66a10872ebdcb5f8ee0e612ecb95a6029 Mon Sep 17 00:00:00 2001 From: Adrian Gonzalez Date: Thu, 9 Jul 2015 16:49:11 -0700 Subject: [PATCH] add test for long cache keys --- lib/cached_resource/caching.rb | 12 ++++++++++-- spec/cached_resource/caching_spec.rb | 9 +++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) 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