lib/zendesk_api/collection.rb in zendesk_api-0.1.2 vs lib/zendesk_api/collection.rb in zendesk_api-0.1.3

- old
+ new

@@ -81,17 +81,19 @@ end # Changes the per_page option. Returns self, so it can be chained. No execution. # @return [Collection] self def per_page(count) + clear_cache if count @options["per_page"] = count self end # Changes the page option. Returns self, so it can be chained. No execution. # @return [Collection] self def page(number) + clear_cache if number @options["page"] = number self end # Saves all newly created resources stored in this collection. @@ -142,29 +144,62 @@ else path = self.path end response = @client.connection.send(@verb || "get", path) do |req| - req.params.merge!(@options.delete_if {|k, v| v.nil?}) + opts = @options.delete_if {|k, v| v.nil?} + + if %w{put post}.include?(@verb.to_s) + req.body = opts + else + req.params.merge!(opts) + end end results = response.body[@resource_class.model_key] || response.body["results"] @resources = results.map { |res| @resource_class.new(@client, res) } @count = (response.body["count"] || @resources.size).to_i @next_page, @prev_page = response.body["next_page"], response.body["previous_page"] + if @next_page =~ /page=(\d+)/ + @options["page"] = $1.to_i - 1 + elsif @prev_page =~ /page=(\d+)/ + @options["page"] = $1.to_i + 1 + end + @resources end rescue_client_error :fetch, :with => lambda { Array.new } # Alias for fetch(false) def to_a fetch end + # Calls #each on every page with the passed in block + # @param [Block] block Passed to #each + def each_page(&block) + page(nil) + clear_cache + + while !empty? + each do |resource| + arguments = [resource, @options["page"] || 1] + + if block.arity >= 0 + arguments = arguments.take(block.arity) + end + + block.call(*arguments) + end + + self.next + end + end + def replace(collection) raise "this collection is for #{@resource_class}" if collection.any?{|r| !r.is_a?(@resource_class) } @resources = collection end @@ -178,26 +213,28 @@ @options["page"] += 1 elsif @next_page @query = @next_page fetch(true) else - [] + clear_cache + @resources = [] end end - # Find the previous page. Does one of three things: + # Find the previous page. Does one of three things: # * If there is already a page number in the options hash, it increases it and invalidates the cache, returning the new page number. # * If there is a prev_page url cached, it executes a fetch on that url and returns the results. # * Otherwise, returns an empty array. def prev - if @options["page"] && @options["page"] > 1 + if @options["page"] && @options["page"] > 1 clear_cache @options["page"] -= 1 elsif @prev_page @query = @prev_page fetch(true) else - [] + clear_cache + @resources = [] end end # Clears all cached resources and associated values. def clear_cache