我试图调用一个方法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)
如何完成摘要后如何获得摘要?