Sha256: 6ef697e15fb08c6617a99b2822eab5ab3293b946ab1dd0c9f29f1a693a2d6ce6

Contents?: true

Size: 1.44 KB

Versions: 4

Compression:

Stored size: 1.44 KB

Contents

# ApiClient::Collection handle a collection of objects
class ApiClient::Collection < Array
  # Initialize a collection of objects based on attributes.
  #
  # @param [Hash/Array] the hash or array of attributes.
  # @param [Class] klass The class to instantiate the objects.
  # @return [Collection] the collection of objects.
  def initialize(attributes, klass)
    @klass = klass
    update(attributes)
  end

  # Update the collection of objects based on the new attributes.
  #
  # @param [Hash/Array] the hash or array of attributes.
  # @return [Collection] the collection of objects.
  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

  # Initialize some variables based on attributes.
  #
  # @param [Hash] the hash of attributes.
  # @return [Hash] the hash of attributes without pagination attributes.
  def pagination_attributes(attributes)
    @total = attributes.delete("total")
    @total_pages = attributes.delete("total_pages")
    @offset = attributes.delete("offset")
    @_links = attributes.delete("_links")
    attributes
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
api-client-3.1.0 lib/api-client/collection.rb
api-client-3.0.0 lib/api-client/collection.rb
api-client-2.7.0 lib/api-client/collection.rb
api-client-2.6.0 lib/api-client/collection.rb