Skip to content

Commit 240f3aa

Browse files
committed
cache client resources based on options as well
1 parent ec3deb2 commit 240f3aa

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

lib/zendesk_api/client.rb

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,14 @@ class Client
3131
def method_missing(method, *args, &block)
3232
method = method.to_s
3333
options = args.last.is_a?(Hash) ? args.pop : {}
34-
return instance_variable_get("@#{method}") if !options.delete(:reload) && instance_variable_defined?("@#{method}")
35-
instance_variable_set("@#{method}", ZendeskAPI::Collection.new(self, ZendeskAPI.get_class(Inflection.singular(method)), options))
34+
35+
@resource_cache[method] ||= {}
36+
37+
if !options[:reload] && (cached = @resource_cache[method][options.hash])
38+
cached
39+
else
40+
@resource_cache[method][options.hash] = ZendeskAPI::Collection.new(self, ZendeskAPI.get_class(Inflection.singular(method)), options)
41+
end
3642
end
3743

3844
# Returns the current user (aka me)
@@ -86,6 +92,8 @@ def initialize
8692

8793
@callbacks = []
8894

95+
@resource_cache = {}
96+
8997
if logger = config.logger
9098
insert_callback do |env|
9199
if warning = env[:response_headers]["X-Zendesk-API-Warn"]

spec/client_spec.rb

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def build_connection
117117
context "with a logger" do
118118
let(:out){ StringIO.new }
119119
subject { Logger.new(out) }
120-
120+
121121
it "should log" do
122122
@client.connection.builder.handlers.should include(ZendeskAPI::Middleware::Response::Logger)
123123
end
@@ -154,8 +154,19 @@ def build_connection
154154

155155
context "resources" do
156156
it "should return an instance of ZendeskAPI::Collection if there is no method" do
157+
subject.instance_variable_get(:@resource_cache)["tickets"].should be_nil
158+
157159
subject.tickets.should be_instance_of(ZendeskAPI::Collection)
158-
subject.instance_variable_defined?(:@tickets).should be_true
160+
161+
subject.instance_variable_get(:@resource_cache)["tickets"].should_not be_empty
162+
end
163+
164+
it "should not cache calls with different options" do
165+
subject.search(:query => 'abc').should_not == subject.search(:query => '123')
166+
end
167+
168+
it "should cache calls with the same options" do
169+
subject.search(:query => 'abc').should == subject.search(:query => 'abc')
159170
end
160171
end
161172

0 commit comments

Comments
 (0)