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.



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

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)



12
13
14
# File 'lib/asana/resource_includes/collection.rb', line 12

def elements
  @elements
end

Instance Method Details

#each(&block) ⇒ Object

Iterates over the elements of the collection.



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

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.



42
43
44
# File 'lib/asana/resource_includes/collection.rb', line 42

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.



47
48
49
# File 'lib/asana/resource_includes/collection.rb', line 47

def size
  to_a.size
end

#to_sObject Also known as: inspect

Returns a String representation of the collection.



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

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