Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Monkeypatching Net::HTTP to play ball with EventMachine.

tag: v0.2.3

Fetching latest commit…

Octocat-spinner-32-eaf2f5

Cannot retrieve the latest commit at this time

Octocat-spinner-32 lib
Octocat-spinner-32 spec
Octocat-spinner-32 .document
Octocat-spinner-32 .gitignore
Octocat-spinner-32 Gemfile
Octocat-spinner-32 LICENSE
Octocat-spinner-32 README.md
Octocat-spinner-32 Rakefile
Octocat-spinner-32 VERSION
Octocat-spinner-32 em-net-http.gemspec
README.md

Most Ruby web API libraries use Net::HTTP (because it's ubiquitous), but I want to use them in my non-blocking EventMachine-based applications, and I don't want Net::HTTP to block. I therefore wrote this.

Using the magic of Ruby 1.9's Fibers, we monkeypatch Net::HTTP to use the faster, nonblocking em-http-request under the hood. Obviously this will only work from inside the EventMachine event loop, and from within a spawned fiber:

require 'em-net-http'

EM.run do
  Fiber.new do
    Net::HTTP.start('encrypted.google.com', :use_ssl=>true) do |http|
      res = http.get('/search?q=james')
      puts res.body
    end
    EM.stop_event_loop
  end.resume
end

The above will run without blocking your carefully-tuned nonblocking webapp.

There are a few tests (taking advantage of Luke Redpath's very useful Mimic gem) that assert that responses are identical to those created by Net::HTTP. These are by no means exhaustive; if you're using Net::HTTP in some other way and the em-net-http's behaviour is not what you expect, do send me a failing test case.

Currently tested with Ruby (MRI) 1.9.1 and 1.9.2.

Caveat

The Net::HTTP API is a many-headed hydra -- I haven't patched much of it; in fact I've patched Net::HTTP#request, and that's it. Your mileage may therefore vary. Please feed me patches, pull requests and bug reports!

Something went wrong with that request. Please try again.