2016-03-05 28 views
0

我有一種方法,一次只能加載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 
+0

解釋這些變量/方法。 – sawa

回答

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 

您可以省略塊參數,並使用yield(如下所示),但爲了清楚起見,我更願意將其放在方法簽名中。

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

我會很樂意接受你的答案,但是你會關心這個方法的一個粗略的例子,因爲紅寶石塊對我來說仍然有點神祕。 – Besi

+0

@Besi增加了一些代碼 – Leventix