Skip to content

Instantly share code, notes, and snippets.

@jordanstephens
Last active July 25, 2023 15:46
Show Gist options
  • Save jordanstephens/eb99735fc7407222b510ad61f7509498 to your computer and use it in GitHub Desktop.
Save jordanstephens/eb99735fc7407222b510ad61f7509498 to your computer and use it in GitHub Desktop.
LazyPager
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