Skip to content

Instantly share code, notes, and snippets.

@uu59
Created December 20, 2011 10:33
Show Gist options
  • Save uu59/1501118 to your computer and use it in GitHub Desktop.
Save uu59/1501118 to your computer and use it in GitHub Desktop.
# https://github.com/igrigorik/em-http-request/blob/master/examples/fibered-http.rb
require "pp"
require "rubygems"
require "eventmachine"
require "em-http"
require "fiber"
module Foo
EM < ::EventMachine
def http(&block)
@count = 0
EM.run do
instance_eval(&block)
end
end
def request(method, url, params={}, block)
@count += 1
Fiber.new do
f = Fiber.current
con = EM::HttpRequest.new(url)
http = con.__send__(method)
http.callback { f.resume }
http.errback{ f.resume }
Fiber.yield
block.call(http)
@count -= 1
EM.stop if @count == 0
end.resume
end
%w!get post head put delete!.each do |method|
instance_eval <<-RUBY
def #{method}(url, params={}, &block)
request(:#{method}, url, params, block)
end
RUBY
end
extend self
end
Foo.http do
get("http://www.google.com/") do |http|
pp http.response_header
end
get("http://www.google.com/search?q=test") do |http|
pp http.response_header
end
get("http://www.yahoo.com/") do |http|
pp http.response_header
end
%w!http://bing.com/ http://yandex.ru/!.each do |url|
get(url) do |http|
pp http.response_header
end
end
end
puts "done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment