Search code examples
rubyeventmachine

Return eventmachine output to object in Ruby


In the below function (which is defined inside a class Myclass) I can run the function in ruby like

myoutput =  Myclass.get_par("http://eol.org/api/ping/1.0.json,http://eol.org/api/ping/1.0.json")

and the output of the calls gets printed to the terminal, but I the output is not assigned to the object myoutput.

is there a way to make the output return to an object, and not just print?

def self.get_par(urls)
  allurls = urls.split(',')
  results = []
  EM.synchrony do
    concurrency = 2
    results << EM::Synchrony::Iterator.new(allurls, concurrency).map do |url, iter|
      http = EventMachine::HttpRequest.new(url).aget
      http.callback { iter.return(http.response) }
      http.errback { iter.return(http) }
    end
    EventMachine.stop
    puts results # all completed requests
  end
end

Solution

  • puts returns nil, so returning the results of puts won't do much for you.

    Return results instead, or do both, e.g.,

    def self.get_par(urls)
      # ... etc ...
      puts results
      results
    end