Class: ApiClient::Collection

Inherits:
Array
  • Object
show all
Defined in:
lib/api-client/collection.rb

Overview

ApiClient::Collection handle a collection of objects

Instance Method Summary collapse

Constructor Details

#initialize(attributes, klass) ⇒ Collection

Initialize a collection of objects based on attributes.

Parameters:

  • the (Hash/Array)

    hash or array of attributes.

  • klass (Class)

    The class to instantiate the objects.


8
9
10
11
# File 'lib/api-client/collection.rb', line 8

def initialize(attributes, klass)
  @klass = klass
  update(attributes)
end

Instance Method Details

#pagination_attributes(attributes) ⇒ Hash

Initialize some variables based on attributes.

Parameters:

  • the (Hash)

    hash of attributes.

Returns:

  • (Hash)

    the hash of attributes without pagination attributes.


38
39
40
41
42
43
44
# File 'lib/api-client/collection.rb', line 38

def pagination_attributes(attributes)
  @total = attributes.delete("total")
  @total_pages = attributes.delete("total_pages")
  @offset = attributes.delete("offset")
  @_links = attributes.delete("_links")
  attributes
end

#update(attributes) ⇒ Collection

Update the collection of objects based on the new attributes.

Parameters:

  • the (Hash/Array)

    hash or array of attributes.

Returns:


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/api-client/collection.rb', line 17

def update(attributes)
  self.clear
  @response = attributes
  if attributes.instance_of?(Array)
    attributes.each do |attr|
      self << @klass.new(attr)
    end
  elsif attributes[@klass.name.pluralize.downcase].instance_of?(Array)
    attributes = pagination_attributes(attributes)
    attributes[@klass.name.pluralize.downcase].each do |attr|
      self << @klass.new(attr)
    end
  else
    self << @klass.new(attributes)
  end
end