Skip to content

Instantly share code, notes, and snippets.

@notahat
Created March 15, 2013 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notahat/5166594 to your computer and use it in GitHub Desktop.
Save notahat/5166594 to your computer and use it in GitHub Desktop.
class PagingEnumerator < Enumerator
def initialize(&block)
super do |yielder|
page = 0
loop do
items = block.call(page)
break if items.empty?
items.each {|item| yielder.yield(item) }
page += 1
end
end
end
def lazy_reject(&block)
Enumerator.new do |yielder|
each do |object|
yielder.yield(object) unless block.call(object)
end
end
end
end
describe PagingEnumerator do
it "iterates through each page" do
enumerator = PagingEnumerator.new {|page| [1, 2, 3] }
enumerator.take(6).should == [1, 2, 3, 1, 2, 3]
end
it "passes a page number to the block" do
enumerator = PagingEnumerator.new {|page| [page] }
enumerator.take(3).should == [0, 1, 2]
end
it "stops at a blank page" do
enumerator = PagingEnumerator.new {|page| page == 0 ? [1, 2, 3] : [] }
enumerator.take(6).should == [1, 2, 3]
end
context "#lazy_reject" do
it "rejects objects that for which the block returns true" do
enumerator = PagingEnumerator.new {|page| [1, 2, 3] }
enumerator.lazy_reject {|n| n == 2 }.take(6).should == [1, 3, 1, 3, 1, 3]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment