Class: Asana::Resources::Collection

Inherits:
Object
  • Object
show all
Includes:
ResponseHelper, Enumerable
Defined in:
lib/asana/resource_includes/collection.rb

Overview

Represents a paginated collection of Asana resources.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ResponseHelper

#parse

Constructor Details

#initialize(elements, extra, type: Resource, client: required('client')) ⇒ Collection

Initializes a collection representing a page of resources of a given type.

(elements, extra) - [Array] an (String, Hash) tuple coming from the

response parser.

Parameters:

  • type (Class) (defaults to: Resource)

    the type of resource that the collection contains. Defaults to the generic Resource.

  • client (Asana::Client) (defaults to: required('client'))

    the client to perform requests.


20
21
22
23
24
25
26
27
# File 'lib/asana/resource_includes/collection.rb', line 20

def initialize((elements, extra),
               type: Resource,
               client: required('client'))
  @elements       = elements.map { |elem| type.new(elem, client: client) }
  @type           = type
  @next_page_data = extra['next_page']
  @client         = client
end

Instance Attribute Details

#elementsObject (readonly)


10
11
12
# File 'lib/asana/resource_includes/collection.rb', line 10

def elements
  @elements
end

Instance Method Details

#each(&block) ⇒ Object

Iterates over the elements of the collection.


30
31
32
33
34
35
36
37
# File 'lib/asana/resource_includes/collection.rb', line 30

def each(&block)
  if block
    @elements.each(&block)
    (next_page || []).each(&block)
  else
    to_enum
  end
end

#lastObject

Returns the last item in the collection.


40
41
42
# File 'lib/asana/resource_includes/collection.rb', line 40

def last
  @elements.last
end

#next_pageObject

Returns a new Asana::Resources::Collection with the next page or nil if there are no more pages. Caches the result.


60
61
62
63
64
65
66
67
68
69
# File 'lib/asana/resource_includes/collection.rb', line 60

def next_page
  if defined?(@next_page)
    @next_page
  else
    @next_page = if @next_page_data
                   response = parse(@client.get(@next_page_data['path']))
                   self.class.new(response, type: @type, client: @client)
                 end
  end
end

#sizeObject Also known as: length

Returns the size of the collection.


45
46
47
# File 'lib/asana/resource_includes/collection.rb', line 45

def size
  to_a.size
end

#to_sObject Also known as: inspect

Returns a String representation of the collection.


51
52
53
54
55
# File 'lib/asana/resource_includes/collection.rb', line 51

def to_s
  "#<Asana::Collection<#{@type}> " \
    "[#{@elements.map(&:inspect).join(', ')}" +
    (@next_page_data ? ', ...' : '') + ']>'
end