我试图调用一个方法,from_server,给它一个可以接受结果的块。from_server 从 api 加载项目列表,然后为列表中的每个调用一个函数 add_update 给它一个块来接受每个细节的结果。处理完所有细节后,from_server 调用其块返回摘要。
我可以让低水平工作正常。我的问题是第一个函数在一切完成之前调用它的块。
不知道为什么或在哪里需要放置 block.call
主要来电者
from_server do |updates, inserts|
puts "\n Updates = #{updates}"
puts " Inserts = #{inserts}\n\n"
puts 'all Done'
end
from_server 函数调用
def from_server(&block)
inserts = 0
updates = 0
channels = [1,2,4,6,7]
for channels.each do
add_update("/api/channels/#{channel}", &block) do |added, channel|
if added
inserts += 1
else
updates += 1
end
#do some things with channel
end
block.call(updates, inserts) unless block.nil? # problem is here gets returned as soon as all channels have been started on a thread
end
end
获取列表并处理每个项目
def from_server(&block)
uri = '/api/channels'
ApiRequest.get(uri) do |header, body|
new_count = 0
update_count = 0
puts "\nList Body = #{body}\n"
body.each do |channel|
add_update(channel['uri']) do |new, ad_channel|
if new
puts "\nNew #{ad_channel}"
new_count += 1
else
puts "\nUpdate #{ad_channel}"
update_count += 1
end
puts
end
end
puts "\nDONE\n"
block.call(update_count, new_count) unless block.nil?
puts "All Requests Done\n"
end
puts "Request all channels started"
end
处理每个项目
def add_update(channel_uri, &block)
ApiRequest.get(channel_uri) do |header, body|
if ad_channel = AdvChannel.find(name: body['name']).first
puts "\n#{ad_channel.name} already exists"
new = false
else
ad_channel = AdvChannel.create(name: body['name'],
phone: body['phone'],
url: body['uri'],
admin_url: body['admin_url'],
channel_code: body['channel_code'],
uri: channel_uri)
puts "\nInserting #{ad_channel.name} - #{ad_channel.id}"
new = true
end
block.call(new, ad_channel) if block_given?
end
执行调用者的结果是:给我以下内容:
Request all channels started immediately (expected)
the List Body string (expected)
Add update one started (expected)
DONE (unexpected should be after all are done)
Updates = 0 (unexpected should be after all are done)
Inserts = 0 (unexpected should be after all are done)
all Done (unexpected should be after all are done)
All Requested Done (unexpected should be after all are done)
the insert or update information for each channel (expected)
完成后如何获得摘要?