Class: Seq::Paged
Overview
Paged seqs evaluate a block that returns a page (Array) of items that are then returned one at a time. This is useful for working with web services that return pages of results, when you need them as a list.
Constant Summary
Constants inherited from Seq
Instance Method Summary collapse
-
#each ⇒ Object
Iterates over each item as returned by #next until #ended?.
-
#ended? ⇒ Boolean
Whether the Paged seq has returned all of its items.
-
#initialize(offset = 0, default = nil) {|page| ... } ⇒ Paged
constructor
Creates a new Paged seq instance.
-
#next ⇒ Object
Until ended it return the next item in the paged list.
-
#reset ⇒ Object
Resets the state of the paged seq.
Methods inherited from Seq
#entries, #inc, #infinite?, #method_missing, #to_a
Constructor Details
#initialize(offset = 0, default = nil) {|page| ... } ⇒ Paged
Creates a new Paged seq instance.
35 36 37 38 39 40 41 |
# File 'lib/seq/paged.rb', line 35 def initialize(offset=0, default=nil, &block) @block = block @offset = offset @default = default self.reset end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method in the class Seq
Instance Method Details
#each ⇒ Object
Iterates over each item as returned by #next until #ended?.
57 58 59 60 61 62 63 |
# File 'lib/seq/paged.rb', line 57 def each loop do val = self.next return if self.ended? yield val end end |
#ended? ⇒ Boolean
Returns Whether the Paged seq has returned all of its items.
66 67 68 |
# File 'lib/seq/paged.rb', line 66 def ended? @index >= @items.size && @done end |
#next ⇒ Object
Returns Until ended it return the next item in the paged list. If ended it returns the default value.
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/seq/paged.rb', line 72 def next return @default if ended? while @items.size <= @index loaded = @block.call(@page) @page += 1 if loaded.empty? @done = true return @default end @items += loaded end item = @items[@index] @index += 1 item end |
#reset ⇒ Object
Resets the state of the paged seq. It also calculates any values necessary to get to the offset.
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/seq/paged.rb', line 45 def reset @index = 0 @page = 0 @done = false @items = [] until @index >= @offset self.next end end |