-
Notifications
You must be signed in to change notification settings - Fork 183
Collections
A Collection is a lazy-loaded array of resources (e.g. Tickets, Users, ...) with some helper methods for pagination. Actual requests may not be sent until an explicit ZendeskAPI::Collection#fetch, ZendeskAPI::Collection#to_a, or an applicable methods such as #each.
Collections can be automatically instantiated through a Client instance by using the helper methods.
The helper methods are generated using the top-level resource classes. For example, to create a
collection of tickets you can call client.tickets
, and for users client.users
.
Collections can also be created directly:
ZendeskAPI::Collection.new(client, ZendeskAPI::Ticket)
Some options can also be passed:
# POST /api/v2/topics/show_many?ids=1
ZendeskAPI::Collection.new(client, ZendeskAPI::Topic, :ids => [1], :path => "topics/show_many", :verb => :post)
API endpoints such as tickets/recent or topics/show_many can be accessed through chaining. They will too return an instance of ZendeskAPI::Collection.
client.tickets.recent # GET /api/v2/tickets/recent
client.topics.show_many(:verb => :post, :ids => [1, 2, 3]) # POST /api/v2/topics/show_many?ids=1,2,3
Resources can be added to Collections using #<< in two different ways:
Adding an explicit Resource object:
ticket = ZendeskAPI::Ticket.new(client, :subject => "Help!")
tickets = client.tickets
tickets << ticket
Adding an options hash:
tickets = client.tickets
tickets << { :subject => "Help!" }
Resources can then be saved with Collection#save or Collection#save!.
Collections have #page and #per_page methods that will clear the cache and be applied on the next HTTP request. Both #page and #per_page can be chained as they will return the same collection instance.
Collections also have #next and #prev methods that, depending on the current state, will do one of the following:
- If there is already a page number in the options hash, it increases/decreases it by one and invalidates the cache, returning the new page number.
- If there is a next_page url cached, it executes a fetch on that url (inside the same collection instance) and returns the results.
- Otherwise, the existing cache is invalidated.
tickets = client.tickets.page(2).per_page(3)
next_page = tickets.next # => 3
tickets.fetch # GET /api/v2/tickets?page=3&per_page=3
previous_page = tickets.prev # GET /api/v2/tickets?page=2&per_page=3
Iteration over all resources and pages is handled by Collection#all
client.tickets.all do |resource|
# every resource, from all pages, will be yielded to this block
end
If given a block with two arguments, the page number is also passed in.
client.tickets.all do |resource, page_number|
# all resources will be yielded along with the page number
end
See Side-Loading.