ruby中的分页资源负载

时间:2016-03-05 11:39:51

标签: ruby loops conceptual

我有一个只能一次加载50个对象的方法。

所以我提出了这段红宝石代码,以便在没有更多结果的情况下继续加载:

objects = []
offset = 0
limit = 50

loop do 
  # Load paged objects using the current given offset
  new_objects = load_objects(some_url, limit: limit, start: offset)  
  offset += limit
  objects.concat(new_objects)

  # End the loop as soon as no more results are returned
  break if new_objects.count == 0
end 

现在虽然这很有效,但我想知道在ruby中是否有更简洁的方法来完成这项任务。

更新:我在想一些collect - 像这样的方法:

# Pseudocode
objects = update_while_true([],0) do |result_array, limit|
    new_objects = load_objects(some_url, limit: 50, start: current)
    result_array.concat(new_objects)
    limit += 50

    # Should the loop be run again?
    new_objects.count > 0
end

1 个答案:

答案 0 :(得分:1)

我会把它提取到一个方法中,所以你的代码看起来像这样:

limit = 50
objects = until_there_are_no_more_results do |offset|
  load_objects(some_url, limit: limit, start: offset)
end

提取的方法将包含非常通用的代码,类似于此(未经测试):

def until_there_are_no_more_results(&loader_proc)
  objects = []
  offset = 0

  loop do
    # Load paged objects using the current given offset
    new_objects = loader_proc.call(offset) # or: yield(offset)
    offset += limit
    objects.concat(new_objects)

    # End the loop as soon as no more results are returned
    break if new_objects.count == 0
  end

  objects
end

您可以省略block参数并使用yield,如下所示,但为了清晰起见,我更喜欢将其放在方法签名中。

def until_there_are_no_more_results
  #...
    new_objects = yield(offset)