如何根据红宝石返回的结果量进行循环

时间:2019-01-19 17:40:39

标签: ruby-on-rails ruby

我正在尝试使其能够从api获取所有信息。我需要循环api调用,直到收到少于1000行。问题是api只返回1000行,我不知道它可以发送多少行,但是我可以抵消每个api调用。

我正在尝试使它多次调用API并返回所有内容。下面是我到目前为止的工作。

  response1 = External::getdataApi.call({country_ids: 'gb', extras: 'hotel_info'})
  response1 = response1.instance_variable_get(:@response)
  if response1['result'].count == 1000
    response1 = External::getdataApi.call({country_ids: 'gb', extras: 'hotel_info', offset: 1000})
  end

需要进行的工作是一旦被调用,就需要再次调用,直到结果少于1000。此时将保存剩余的行,然后退出循环。

2 个答案:

答案 0 :(得分:1)

您可以使用upto method on Integer来实现。您的代码如下所示:

MAX = 100 # or whatever is reasonable
1.upto(MAX) do |index|
  offset = index * 1000
  response1 = External::getdataApi.call({country_ids: 'gb', extras: 'hotel_info', offset: offset})
  response1 = response1.instance_variable_get(:@response)

  # process response

  break if response1['result'].count != 1000
end

Ruby 2.6 also has the concept of infinity,如果您使用的是1.upto(MAX),则可以将其替换为(1..).each

答案 1 :(得分:0)

您可以使用while循环,如下所示:

offset = 0
end_reached = false

while !end_reached
    response1 = External::getdataApi.call({country_ids: 'gb', extras: 'hotel_info', offset: offset})
    response1 = response1.instance_variable_get(:@response)

    # increase offset by 1000
    offset += 1000

    # if result count is different from 1000 means the end was reached, set end_reached var to true so loop ends
    end_reached = true if response1['result'].count != 1000
end

或这样的until循环:

offset = 0
end_reached = false

until end_reached
    response1 = External::getdataApi.call({country_ids: 'gb', extras: 'hotel_info', offset: offset})
    response1 = response1.instance_variable_get(:@response)

    # increase offset by 1000
    offset += 1000

    # if result count is different from 1000 means the end was reached, set end_reached var to true so loop ends
    end_reached = true if response1['result'].count != 1000
end

我喜欢最后一个,因为我认为它读起来更好