Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion 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,7 +114,16 @@ def cache_clear

# Generate the request cache key.
def cache_key(*arguments)
"#{name.parameterize.gsub("-", "/")}/#{arguments.join('/')}".downcase.delete(' ')
"#{name.parameterize.gsub("-", "/")}/#{arguments_cache_key(*arguments)}".downcase.delete(' ')
end

def arguments_cache_key(*arguments)
arguments_string = arguments.join('/')
arguments_string.length > MAX_ARGUMENTS_CACHE_SIZE ? hash_string(arguments_string) : arguments_string
end

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