Created
January 30, 2011 01:06
-
-
Save igrigorik/802391 to your computer and use it in GitHub Desktop.
sync / async API with rack-client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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