Skip to content

Instantly share code, notes, and snippets.

@steved
Created December 9, 2010 17:11
Show Gist options
  • Save steved/734988 to your computer and use it in GitHub Desktop.
Save steved/734988 to your computer and use it in GitHub Desktop.
Eventmachine Deferrable example
require 'httparty'
require 'eventmachine'
class Request
include EM::Deferrable
@@requests = []
attr_reader :method, :params
def self.run
return if @@requests.empty?
EM.run do
@@requests.each do |request|
Thread.new do
begin
request.send_request
rescue => e
puts e.backtrace
request.fail({"result" => {"message" => e}})
ensure
@@requests.delete(request)
end
end
end
until @@requests.empty?; end
EM.stop
end
end
def initialize(method, params, &callback)
@method, @params = method, params
self.callback(&callback)
@@requests << self
end
def send_request
@response = HTTParty.get(@method, @params)
if @response["result"]["message"].nil?
succeed(@response)
else
fail(@response)
end
end
end
whoismyrep = 'http://whoismyrepresentative.com/whoismyrep.php'
%w(91108 94026 90274 07620 10014 90210 10065 94920 10012 93108 11568 11013 92067 91302 94022 92661 11976 94024 11932 94010 11765 10003 21056 90265 10021).each do |zip|
req = Request.new(whoismyrep, :query => { :zip => zip }) do |response|
reps = response["result"]["rep"]
if reps.is_a?(Array)
reps.each do |rep|
print "#{zip}: #{rep["name"]} => District #{rep["district"]}, #{rep["phone"]}\n"
end
else
print "#{zip}: #{reps["name"]} => District #{reps["district"]}, #{reps["phone"]}\n"
end
end
req.callback do |response|
rep = response["result"]["rep"]
print "#{zip} is in #{(rep.is_a?(Array) ? rep.first : rep)["state"]}\n"
end
req.errback do |response|
print "#{zip}: #{response["result"]["message"]}\n"
end
end
Request.run
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment