Last active
July 25, 2023 15:46
-
-
Save jordanstephens/eb99735fc7407222b510ad61f7509498 to your computer and use it in GitHub Desktop.
LazyPager
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 LazyPager | |
include Enumerable | |
def initialize(&block) | |
@page = 0 | |
@block = block | |
@items = [] | |
@index = 0 | |
end | |
def each(&block) | |
loop do | |
block.call(next_item) | |
end | |
end | |
private | |
attr_reader :page, :block, :items, :index | |
def next_item | |
if index >= items.length | |
generate_next_page | |
@index = 0 | |
return next_item | |
end | |
items[index].tap do | |
@index += 1 | |
end | |
end | |
def generate_next_page | |
@page += 1 | |
@items = block.call(page) | |
raise StopIteration unless items.is_a?(Enumerable) | |
raise StopIteration if items.empty? | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment