I am new to ruby but the problem which I am trying to solve is bit logical.
I am getting a list of users who count is around 3000. but the api supports the response limit to 250 and also it does not support pagination or offset. So I have to hit this api in a loop such a way that every time I will get 250 records till I reach the count 3000. and on each round I am assigning some attributes to it.
api is a Get Request which fetch the list of users.
api url: {{baseUrl}}/accounts/:id/users?limit=250&offset=0&count=true
api says - offset is record based, not page based,
How can I requests for users such as: First call for 0 to 250 then 250 to 500 then 500 to 750 till we reach the max count.
To generalize this I am thinking that whatever the count I will get it should loop through all and assign attributes.
CodePudding user response:
May be using Range#step
?
require 'uri'
require 'net/http'
(0..3000).step(250) do |offset|
uri = URI("#{base_url}/accounts/users?limit=250&offset=#{offset}")
res = Net::HTTP.get_response(uri)
puts res.body if res.is_a?(Net::HTTPSuccess)
end
Or may be such way with endless range
(0..).step(250) do |offset|
uri = URI("#{base_url}/accounts/users?limit=250&offset=#{offset}")
res = Net::HTTP.get_response(uri)
if res.is_a?(Net::HTTPSuccess)
puts res.body
else
break
end
end
You can also can use redo
in the block to repeat bad request
CodePudding user response:
You can use Numeric#step
to enumerate a sequence of offsets [0, 250, 500... 2750]
. Then, assuming get_stuff
returns an Array
, you can stitch the results using Enumerator#flat_map
:
stuff = 0.step(by:250, to:2999).flat_map do |offset|
get_stuff(offset, 250)
end