Ruby EventMachine - how to return values ​​from EM :: Snooze to main EM loop?

I have been playing with EventMachine for several days now, which has a steep IMHO learning curve ;-) I'm trying to return a hash by calling HttpHeaderCrawler.query (), which I need in the callback. But in this case, I get not the hash {'http_status' => xxx, 'http_version' => xxx}, but the EventMachine :: HttpClient object itself.

I want to keep the EM.run block clean and I want to do all the logic within my own classes / modules, so how can I return such a value to the main loop to get a callback to it? Thank you very much in advance; -)

#!/usr/bin/env ruby require 'eventmachine' require 'em-http-request' class HttpHeaderCrawler include EM::Deferrable def query(uri) http = EM::HttpRequest.new(uri).get http.callback do http_header = { "http_status" => http.response_header.http_status, "http_version" => http.response_header.http_version } puts "Returns to EM main loop: #{http_header}" succeed(http_header) end end end EM.run do domains = ['http://www.google.com', 'http://www.facebook.com', 'http://www.twitter.com'] domains.each do |domain| hdr = HttpHeaderCrawler.new.query(domain) hdr.callback do |header| puts "Received from HttpHeaderCrawler: #{header}" end end end 

This snippet outputs the following result:

 Returns to EM main loop: {"http_status"=>302, "http_version"=>"1.1"} Received from HttpHeaderCrawler: #<EventMachine::HttpClient:0x00000100d57388> Returns to EM main loop: {"http_status"=>301, "http_version"=>"1.1"} Received from HttpHeaderCrawler: #<EventMachine::HttpClient:0x00000100d551a0> Returns to EM main loop: {"http_status"=>200, "http_version"=>"1.1"} Received from HttpHeaderCrawler: #<EventMachine::HttpClient:0x00000100d56280> 
+4
source share
1 answer

I think the #query problem returns http.callback , which returns the http object itself, whereas it should return self , i.e. an HttpHeaderCrawler. See if this works.

 def query(uri) http = EM::HttpRequest.new(uri).get http.callback do http_header = { "http_status" => http.response_header.http_status, "http_version" => http.response_header.http_version } puts "Returns to EM main loop: #{http_header}" succeed(http_header) end self end 
+7
source

All Articles