Class: ZendeskAPI::Collection

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

Overview

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

Constant Summary collapse

SPECIALLY_JOINED_PARAMS =

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

[:ids, :only]

Instance Attribute Summary collapse

Instance Method Summary collapse

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.



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

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.



301
302
303
304
305
306
307
308
309
# File 'lib/zendesk_api/collection.rb', line 301

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:



15
16
17
# File 'lib/zendesk_api/collection.rb', line 15

def association
  @association
end

#errorZendeskAPI::ClientError (readonly)

Returns The last response error.

Returns:

  • (ZendeskAPI::ClientError)

    The last response error



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

def error
  @error
end

#optionsHash (readonly)

Returns query options.

Returns:

  • (Hash)

    query options



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

def options
  @options
end

#responseFaraday::Response (readonly)

Returns The last response.

Returns:

  • (Faraday::Response)

    The last response



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

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



162
163
164
165
166
167
168
169
170
171
172
173
174
# File 'lib/zendesk_api/collection.rb', line 162

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



228
229
230
# File 'lib/zendesk_api/collection.rb', line 228

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



222
223
224
# File 'lib/zendesk_api/collection.rb', line 222

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



87
88
89
90
91
# File 'lib/zendesk_api/collection.rb', line 87

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



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

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.



283
284
285
286
287
288
289
# File 'lib/zendesk_api/collection.rb', line 283

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).



106
107
108
109
# File 'lib/zendesk_api/collection.rb', line 106

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).



112
113
114
115
# File 'lib/zendesk_api/collection.rb', line 112

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

#each_page(*args, &block) ⇒ Object



237
238
239
240
# File 'lib/zendesk_api/collection.rb', line 237

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



232
233
234
235
# File 'lib/zendesk_api/collection.rb', line 232

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

#fetch(*args) ⇒ Object



202
203
204
205
206
207
208
# File 'lib/zendesk_api/collection.rb', line 202

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



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
# File 'lib/zendesk_api/collection.rb', line 183

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

  @response = get_response(path_query_link)

  if path_query_link == "search/export"
    handle_cursor_response(@response.body)
  else
    handle_response(@response.body)
  end

  @resources
end

#first_page?Boolean

Returns:

  • (Boolean)


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

def first_page?
  !@prev_page
end

#get_next_page_data(original_response_body) ⇒ Object



338
339
340
341
342
343
344
345
346
347
348
349
350
# File 'lib/zendesk_api/collection.rb', line 338

def get_next_page_data(original_response_body)
  link = original_response_body["links"]["next"]

  while link
    response = get_response_body(link)

    original_response_body["results"] = original_response_body["results"] + response["results"]

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

  original_response_body
end

#get_response_body(link) ⇒ Object



334
335
336
# File 'lib/zendesk_api/collection.rb', line 334

def get_response_body(link)
  @client.connection.send("get", link).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



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

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

#last_page?Boolean

Returns:

  • (Boolean)


137
138
139
# File 'lib/zendesk_api/collection.rb', line 137

def last_page?
  !@next_page || @next_page == @query
end

#more_results?(response) ⇒ Boolean Also known as: has_more_results?

Returns:

  • (Boolean)


329
330
331
# File 'lib/zendesk_api/collection.rb', line 329

def more_results?(response)
  response["meta"].present? && response["results"].present?
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.



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

def next
  if @options["page"]
    clear_cache
    @options["page"] += 1
  elsif (@query = @next_page)
    fetch(true)
  else
    clear_cache
    @resources = []
  end
end

#page(number) ⇒ Collection

Changes the page option. Returns self, so it can be chained. No execution.

Returns:



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

def page(number)
  clear_cache if number
  @options["page"] = number
  self
end

#pathObject

The API path to this collection



177
178
179
# File 'lib/zendesk_api/collection.rb', line 177

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

#per_page(count) ⇒ Collection

Changes the per_page option. Returns self, so it can be chained. No execution.

Returns:



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

def per_page(count)
  clear_cache if count
  @options["per_page"] = count
  self
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.



270
271
272
273
274
275
276
277
278
279
280
# File 'lib/zendesk_api/collection.rb', line 270

def prev
  if @options["page"] && @options["page"] > 1
    clear_cache
    @options["page"] -= 1
  elsif (@query = @prev_page)
    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



245
246
247
248
# File 'lib/zendesk_api/collection.rb', line 245

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)


296
297
298
# File 'lib/zendesk_api/collection.rb', line 296

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

#saveCollection

Saves all newly created resources stored in this collection.

Returns:



143
144
145
# File 'lib/zendesk_api/collection.rb', line 143

def save
  _save
end

#save!Collection

Saves all newly created resources stored in this collection.

Returns:



149
150
151
# File 'lib/zendesk_api/collection.rb', line 149

def save!
  _save(:save!)
end

#to_aObject

Alias for fetch(false)



211
212
213
# File 'lib/zendesk_api/collection.rb', line 211

def to_a
  fetch
end

#to_a!Object

Alias for fetch!(false)



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

def to_a!
  fetch!
end

#to_aryObject



292
293
294
# File 'lib/zendesk_api/collection.rb', line 292

def to_ary
  nil
end

#to_paramObject



325
326
327
# File 'lib/zendesk_api/collection.rb', line 325

def to_param
  map(&:to_param)
end

#to_sObject Also known as: to_str



312
313
314
315
316
317
318
319
320
321
# File 'lib/zendesk_api/collection.rb', line 312

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