ruby 中的分页资源加载
Paged load of resources in ruby
我有一个方法一次只能加载 50
个对象。
所以我想出了这段 ruby 代码来继续加载直到没有更多结果:
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
我会将其提取到一个方法中,因此您的代码将如下所示:
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
您可以省略块参数并像下面那样使用 yield
,但为了清楚起见,我更喜欢将它放在方法签名中。
def until_there_are_no_more_results
#...
new_objects = yield(offset)
我有一个方法一次只能加载 50
个对象。
所以我想出了这段 ruby 代码来继续加载直到没有更多结果:
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
我会将其提取到一个方法中,因此您的代码将如下所示:
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
您可以省略块参数并像下面那样使用 yield
,但为了清楚起见,我更喜欢将它放在方法签名中。
def until_there_are_no_more_results
#...
new_objects = yield(offset)