Class: ZendeskAPI::Collection

Inherits:
Object
  • Object
show all
Includes:
Pagination, Sideloading
Defined in:
lib/zendesk_api/collection.rb,
lib/zendesk_api/pagination.rb

Overview

Represents a collection of resources. Lazily loaded, resources aren’t actually fetched until explicitly needed (e.g. #each, #fetch).

Defined Under Namespace

Modules: Pagination

Constant Summary collapse

SPECIALLY_JOINED_PARAMS =

Options passed in that are automatically converted from an array to a comma-separated list.

[:ids, :only]

Constants included from Pagination

Pagination::DEFAULT_PAGE_SIZE

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Pagination

#first_page?, #last_page?, #more_results?, #page, #per_page

Methods included from Sideloading

included, #set_includes

Constructor Details

#initialize(client, resource, options = {}) ⇒ Collection

Creates a new Collection instance. Does not fetch resources. Additional options are: verb (default: GET), path (default: resource param), page, per_page.

Parameters:

  • client (Client)

    The ZendeskAPI::Client to use.

  • resource (String)

    The resource being collected.

  • options (Hash) (defaults to: {})

    Any additional options to be passed in.



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/zendesk_api/collection.rb', line 33

def initialize(client, resource, options = {})
  @client, @resource_class, @resource = client, resource, resource.resource_path
  @options = SilentMash.new(options)

  set_association_from_options
  join_special_params

  @verb = @options.delete(:verb)
  @includes = Array(@options.delete(:include))

  # Used for Attachments, TicketComment
  if @resource_class.is_a?(Class) && @resource_class.superclass == ZendeskAPI::Data
    @resources = []
    @fetchable = false
  else
    @fetchable = true
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object

Sends methods to underlying array of resources.



274
275
276
277
278
279
280
281
282
# File 'lib/zendesk_api/collection.rb', line 274

def method_missing(name, *args, &block)
  if resource_methods.include?(name)
    collection_method(name, *args, &block)
  elsif [].respond_to?(name, false)
    array_method(name, *args, &block)
  else
    next_collection(name, *args, &block)
  end
end

Instance Attribute Details

#associationZendeskAPI::Association (readonly)

Returns The class association.

Returns:



17
18
19
# File 'lib/zendesk_api/collection.rb', line 17

def association
  @association
end

#errorZendeskAPI::ClientError (readonly)

Returns The last response error.

Returns:

  • (ZendeskAPI::ClientError)

    The last response error



26
27
28
# File 'lib/zendesk_api/collection.rb', line 26

def error
  @error
end

#optionsHash (readonly)

Returns query options.

Returns:

  • (Hash)

    query options



23
24
25
# File 'lib/zendesk_api/collection.rb', line 23

def options
  @options
end

#responseFaraday::Response (readonly)

Returns The last response.

Returns:

  • (Faraday::Response)

    The last response



20
21
22
# File 'lib/zendesk_api/collection.rb', line 20

def response
  @response
end

Instance Method Details

#<<(item) ⇒ Object

Adds an item to this collection

Parameters:

  • item (Hash)

    a customizable set of options

Options Hash (item):

Raises:

  • (ArgumentError)

    if the resource doesn’t belong in this collection



140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/zendesk_api/collection.rb', line 140

def <<(item)
  fetch

  if item.is_a?(Resource)
    if item.is_a?(@resource_class)
      @resources << item
    else
      raise "this collection is for #{@resource_class}"
    end
  else
    @resources << wrap_resource(item, true)
  end
end

#all(start_page = , &block) ⇒ Object

Calls #each on every page with the passed in block

Parameters:

  • block (Block)

    Passed to #each



197
198
199
# File 'lib/zendesk_api/collection.rb', line 197

def all(start_page = @options["page"], &block)
  _all(start_page, &block)
end

#all!(start_page = , &block) ⇒ Object

Calls #each on every page with the passed in block

Parameters:

  • block (Block)

    Passed to #each



191
192
193
# File 'lib/zendesk_api/collection.rb', line 191

def all!(start_page = @options["page"], &block)
  _all(start_page, :bang, &block)
end

#build(opts = {}) ⇒ Object

Convenience method to build a new resource and add it to the collection. Fetches the collection as well.

Parameters:

  • opts (Hash) (defaults to: {})

    Options or attributes to pass



89
90
91
92
93
# File 'lib/zendesk_api/collection.rb', line 89

def build(opts = {})
  wrap_resource(opts, true).tap do |res|
    self << res
  end
end

#build!(opts = {}) ⇒ Object

Convenience method to build a new resource and add it to the collection. Fetches the collection as well.

Parameters:

  • opts (Hash) (defaults to: {})

    Options or attributes to pass



98
99
100
101
102
103
104
105
# File 'lib/zendesk_api/collection.rb', line 98

def build!(opts = {})
  wrap_resource(opts, true).tap do |res|
    fetch!

    # << does a fetch too
    self << res
  end
end

#clear_cacheObject

Clears all cached resources and associated values.



256
257
258
259
260
261
262
# File 'lib/zendesk_api/collection.rb', line 256

def clear_cache
  @resources = nil
  @count = nil
  @next_page = nil
  @prev_page = nil
  @query = nil
end

#countNumber

Returns The total number of resources server-side (disregarding pagination).

Returns:

  • (Number)

    The total number of resources server-side (disregarding pagination).



108
109
110
111
# File 'lib/zendesk_api/collection.rb', line 108

def count
  fetch
  @count || -1
end

#count!Number

Returns The total number of resources server-side (disregarding pagination).

Returns:

  • (Number)

    The total number of resources server-side (disregarding pagination).



114
115
116
117
# File 'lib/zendesk_api/collection.rb', line 114

def count!
  fetch!
  @count || -1
end

#each_page(*args, &block) ⇒ Object



206
207
208
209
# File 'lib/zendesk_api/collection.rb', line 206

def each_page(*args, &block)
  warn "ZendeskAPI::Collection#each_page is deprecated, please use ZendeskAPI::Collection#all"
  all(*args, &block)
end

#each_page!(*args, &block) ⇒ Object



201
202
203
204
# File 'lib/zendesk_api/collection.rb', line 201

def each_page!(*args, &block)
  warn "ZendeskAPI::Collection#each_page! is deprecated, please use ZendeskAPI::Collection#all!"
  all!(*args, &block)
end

#fetch(*args) ⇒ Object



171
172
173
174
175
176
177
# File 'lib/zendesk_api/collection.rb', line 171

def fetch(*args)
  fetch!(*args)
rescue Faraday::ClientError => e
  @error = e

  []
end

#fetch!(reload = false) ⇒ Object

Executes actual GET from API and loads resources into proper class.

Parameters:

  • reload (Boolean) (defaults to: false)

    Whether to disregard cache



161
162
163
164
165
166
167
168
169
# File 'lib/zendesk_api/collection.rb', line 161

def fetch!(reload = false)
  if @resources && (!@fetchable || !reload)
    return @resources
  elsif association && association.options.parent && association.options.parent.new_record?
    return (@resources = [])
  end

  get_resources(@query || path)
end

#get_next_page_data(original_response_body) ⇒ Object



302
303
304
305
306
307
308
309
310
311
312
313
314
# File 'lib/zendesk_api/collection.rb', line 302

def get_next_page_data(original_response_body)
  link = original_response_body["links"]["next"]
  result_key = @resource_class.model_key || "results"
  while link
    response = @client.connection.send("get", link).body

    original_response_body[result_key] = original_response_body[result_key] + response[result_key]

    link = response["meta"]["has_more"] ? response["links"]["next"] : nil
  end

  original_response_body
end

#include(*sideloads) ⇒ Object

Adds an item (or items) to the list of side-loaded resources to request

Parameters:

  • sideloads (Hash)

    a customizable set of options

Options Hash (*sideloads):

  • The (Symbol or String)

    item(s) to sideload



133
134
135
# File 'lib/zendesk_api/collection.rb', line 133

def include(*sideloads)
  tap { @includes.concat(sideloads.map(&:to_s)) }
end

#nextObject

Find the next 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 next_page url cached, it executes a fetch on that url and returns the results.

  • Otherwise, returns an empty array.



223
224
225
226
227
228
229
230
231
232
233
234
235
# File 'lib/zendesk_api/collection.rb', line 223

def next
  if @options["page"] && !cbp_request?
    clear_cache
    @options["page"] = @options["page"].to_i + 1
  elsif (@query = @next_page)
    # Send _only_ url param "?page[after]=token" to get the next page
    @options.page&.delete("before")
    fetch(true)
  else
    clear_cache
    @resources = []
  end
end

#pathObject

The API path to this collection



155
156
157
# File 'lib/zendesk_api/collection.rb', line 155

def path
  @association.generate_path(:with_parent => true)
end

#prevObject

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.



241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/zendesk_api/collection.rb', line 241

def prev
  if !cbp_request? && @options["page"].to_i > 1
    clear_cache
    @options["page"] -= 1
  elsif (@query = @prev_page)
    # Send _only_ url param "?page[before]=token" to get the prev page
    @options.page&.delete("after")
    fetch(true)
  else
    clear_cache
    @resources = []
  end
end

#replace(collection) ⇒ Object

Replaces the current (loaded or not) resources with the passed in collection

Parameters:

  • collection (Hash)

    a customizable set of options

Options Hash (collection):

  • The (Array)

    collection to replace this one with

Raises:

  • (ArgumentError)

    if any resources passed in don’t belong in this collection



214
215
216
217
# File 'lib/zendesk_api/collection.rb', line 214

def replace(collection)
  raise "this collection is for #{@resource_class}" if collection.any? { |r| !r.is_a?(@resource_class) }
  @resources = collection
end

#respond_to_missing?(name, include_all) ⇒ Boolean

Returns:

  • (Boolean)


269
270
271
# File 'lib/zendesk_api/collection.rb', line 269

def respond_to_missing?(name, include_all)
  [].respond_to?(name, include_all)
end

#saveCollection

Saves all newly created resources stored in this collection.

Returns:



121
122
123
# File 'lib/zendesk_api/collection.rb', line 121

def save
  _save
end

#save!Collection

Saves all newly created resources stored in this collection.

Returns:



127
128
129
# File 'lib/zendesk_api/collection.rb', line 127

def save!
  _save(:save!)
end

#to_aObject

Alias for fetch(false)



180
181
182
# File 'lib/zendesk_api/collection.rb', line 180

def to_a
  fetch
end

#to_a!Object

Alias for fetch!(false)



185
186
187
# File 'lib/zendesk_api/collection.rb', line 185

def to_a!
  fetch!
end

#to_aryObject



265
266
267
# File 'lib/zendesk_api/collection.rb', line 265

def to_ary
  nil
end

#to_paramObject



298
299
300
# File 'lib/zendesk_api/collection.rb', line 298

def to_param
  map(&:to_param)
end

#to_sObject Also known as: to_str



285
286
287
288
289
290
291
292
293
294
# File 'lib/zendesk_api/collection.rb', line 285

def to_s
  if @resources
    @resources.inspect
  else
    inspect = []
    inspect << "options=#{@options.inspect}" if @options.any?
    inspect << "path=#{path}"
    "#{Inflection.singular(@resource)} collection [#{inspect.join(',')}]"
  end
end