Created
March 15, 2013 00:45
-
-
Save notahat/5166594 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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