Class: Seq::Paged

Inherits:
Seq
  • Object
show all
Defined in:
lib/seq/paged.rb

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.

Examples:


s = Seq::Paged.new {|page| [page, page+1, page+2] }
s.take(10)  #=> [0, 1, 2,  1, 2, 3,  2, 3, 4,  3]
            #  extra spacing added to show pages

require 'flickraw'
# Authenticate FlickRaw...

f = Seq::Paged.new {|page|
  flickr.people.getPhotos(:user_id => 'me', :page => page).to_a
}
f.next #=> {"id"=>"8688497043", "owner"=>"75695140@N04", ...}
f.take(100).map {|photo| photo['title'] }.grep(/DSC/)
#=> ["DSC01485-edit", "DSC01485", "DSC01482-edit", "DSC01481", ...]

Constant Summary

Constants inherited from Seq

VERSION

Instance Method Summary collapse

Methods inherited from Seq

#each, #entries, #inc, #infinite?, #method_missing, #to_a

Constructor Details

#initialize(offset = 0, default = nil) {|page| ... } ⇒ Paged

Creates a new Paged seq instance.

Parameters:

  • offset (Integer) (defaults to: 0)

    Index of item to start at

  • default (Object) (defaults to: nil)

    Value to return when finished

Yields:

  • (page)

    Block to be called which returns the next page of items

Yield Parameters:

  • page (Integer)

    Page to be returned, begins at 0



33
34
35
36
37
38
39
# File 'lib/seq/paged.rb', line 33

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

#ended?Boolean

Returns Whether the Paged seq has returned all of its items.

Returns:

  • (Boolean)

    Whether the Paged seq has returned all of its items.



55
56
57
# File 'lib/seq/paged.rb', line 55

def ended?
  @index >= @items.size && @done
end

#nextObject

Returns Until ended it return the next item in the paged list. If ended it returns the default value.

Returns:

  • (Object)

    Until ended it return the next item in the paged list. If ended it returns the default value.



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/seq/paged.rb', line 61

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

#resetObject

Resets the state of the paged seq. It also calculates any values necessary to get to the offset.



43
44
45
46
47
48
49
50
51
52
# File 'lib/seq/paged.rb', line 43

def reset
  @index = 0
  @page  = 0
  @done  = false
  @items = []

  until @index >= @offset
    self.next
  end
end