Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@igrigorik
Created January 30, 2011 01:06
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save igrigorik/802391 to your computer and use it in GitHub Desktop.
Save igrigorik/802391 to your computer and use it in GitHub Desktop.
sync / async API with rack-client
require 'rack/client'
require 'yajl'
require 'pp'
require 'eventmachine'
require 'em-synchrony'
require 'em-synchrony/em-http'
module Rack
module Client
class Defaults
include Rack::Client::DualBand
def initialize(app)
@app = app
end
def sync_call(env)
env['QUERY_STRING'] += '&appkey=demo'
response = Response.new(*@app.call(env))
response.finish
end
def async_call(env, &b)
env['QUERY_STRING'] += '&appkey=demo'
@app.call(env) do |response_parts|
response = Response.new(*response_parts)
yield response.finish
end
end
end
end
end
url = "http://api.postrank.com/v2/feed/info?id=igvita.com"
EM.synchrony do
client = Rack::Client.new do
use Rack::Client::Defaults
run Rack::Client::Handler::EmHttp
end
# async request
client.get url do |resp|
pp Yajl::Parser.parse(resp.body)
end
sleep(1)
# fibered sync request via em-synchrony
pp client.get url
EM.stop
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment