Created
December 21, 2022 14:09
-
-
Save elct9620/a02f0b9178455e94036a14cdb580d902 to your computer and use it in GitHub Desktop.
Use Ruby Enumerator to create infinite API loader
This file contains 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
paginator = InfinitePaginator.new( | |
'https://jsonplaceholder.typicode.com/users/%<page>d' | |
) | |
pp paginator.take(12) | |
# => | |
# [{"id"=>1, "name"=>"Leanne Graham"}, | |
# {"id"=>2, "name"=>"Ervin Howell"}, | |
# {"id"=>3, "name"=>"Clementine Bauch"}, | |
# {"id"=>4, "name"=>"Patricia Lebsack"}, | |
# {"id"=>5, "name"=>"Chelsey Dietrich"}, | |
# {"id"=>6, "name"=>"Mrs. Dennis Schulist"}, | |
# {"id"=>7, "name"=>"Kurtis Weissnat"}, | |
# {"id"=>8, "name"=>"Nicholas Runolfsdottir V"}, | |
# {"id"=>9, "name"=>"Glenna Reichert"}, | |
# {"id"=>10, "name"=>"Clementina DuBuque"}, | |
# {"id"=>1, "name"=>"Leanne Graham"}, | |
# {"id"=>2, "name"=>"Ervin Howell"}] |
This file contains 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
require 'json' | |
require 'net/http' | |
class InfinitePaginator | |
include Enumerable | |
attr_reader :page, :per_page | |
def initialize(uri, page: 1, per_page: 10) | |
@uri = uri | |
@page = page | |
@per_page = per_page | |
end | |
def each(&block) | |
stream.each(&block) | |
end | |
def uri | |
URI(format(@uri, page: @page)) | |
end | |
def current_data | |
res = Net::HTTP.get(uri) | |
JSON.parse(res).slice('id', 'name') | |
end | |
def stream | |
@stream ||= Enumerator.new do |y| | |
loop do | |
y.yield current_data | |
@page = (page % per_page) + 1 | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment