Class: HalClient::Collection
- Inherits:
-
Object
- Object
- HalClient::Collection
- 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
-
#count(&blk) ⇒ Object
Returns the number of items in the collection if it is fast to calculate.
-
#each(&blk) ⇒ Object
Iterates over the members of the collection fetching the next page as necessary.
-
#initialize(first_page) ⇒ Collection
constructor
Initializes a collection starting at ‘first_page`.
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 27 |
# File 'lib/hal_client/collection.rb', line 22 def initialize(first_page) (fail NotACollectionError) unless first_page. "item" (fail ArgumentError, "Not the first page of the collection") if first_page. "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.
34 35 36 37 38 39 40 41 42 43 |
# File 'lib/hal_client/collection.rb', line 34 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.("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.
49 50 51 52 53 |
# File 'lib/hal_client/collection.rb', line 49 def each(&blk) each_page do |a_page| a_page.("item").each(&blk) end end |