Class: HalClient::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/hal_client/collection.rb

Overview

Enumerable for items in a paged collection of HAL representations that are encoded using the IANA standard ‘item`, `next` and `prev` link rels.

This will fetch subsequent pages on iteration

Instance Method Summary collapse

Constructor Details

#initialize(first_page) ⇒ Collection

Initializes a collection starting at ‘first_page`.

first_page - The HalClient::Representation of the first page of

the collection to be iterated over.

Raises HalClient::NotACollectionError if ‘first_page` is not a

page of a collection.

Raises ArgumentError if ‘first_page` is some page other than

the first of the collection.


22
23
24
25
26
# File 'lib/hal_client/collection.rb', line 22

def initialize(first_page)
  (fail ArgumentError, "Not the first page of the collection") if first_page.has_related? "prev"

  @first_page = first_page
end

Instance Method Details

#count(&blk) ⇒ Object

Returns the number of items in the collection if it is fast to calculate.

Raises NotImplementedError if any of the pages of the collection

have not already been cached.


33
34
35
36
37
38
39
40
41
42
# File 'lib/hal_client/collection.rb', line 33

def count(&blk)
  (fail NotImplementedError, "Cowardly refusing to make an arbitrary number of HTTP requests") unless all_pages_cached?

  total = 0
  each_page do |p|
    total += p.related("item").count
  end

  total
end

#each(&blk) ⇒ Object

Iterates over the members of the collection fetching the next page as necessary.

Yields the next item of the iteration.



48
49
50
51
52
# File 'lib/hal_client/collection.rb', line 48

def each(&blk)
  each_page do |a_page|
    a_page.related("item").each(&blk) if a_page.related?("item")
  end
end

#sample(*arg) ⇒ Object

Returns one or more randomly selected items from the first page of the collection.

count - number of items to return. If specified return type will

an collection. Default: return a single item


59
60
61
# File 'lib/hal_client/collection.rb', line 59

def sample(*arg)
  first_page.related("item").sample(*arg)
end