Skip to content

Commit

Permalink
add test for long cache keys
Browse files Browse the repository at this point in the history
  • Loading branch information
Adrian Gonzalez committed Dec 2, 2015
1 parent 2fc55b7 commit 64e4b4a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
12 changes: 10 additions & 2 deletions lib/cached_resource/caching.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
9 changes: 9 additions & 0 deletions spec/cached_resource/caching_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -510,4 +518,5 @@ class CustomCollection < ActiveResource::Collection; end
new_result.name.should_not == old_result.name
end
end

end

0 comments on commit 64e4b4a

Please sign in to comment.