Skip to content

Instantly share code, notes, and snippets.

@dmichael
Created June 12, 2009 22:09
Show Gist options
  • Select an option

  • Save dmichael/128966 to your computer and use it in GitHub Desktop.

Select an option

Save dmichael/128966 to your computer and use it in GitHub Desktop.
require 'rubygems'
require 'httparty'
# authority = [ userinfo "@" ] host [ ":" port ]
# http://labs.apache.org/webarch/uri/rfc/rfc3986.html#authority
module HTTPartyHarder
attr_accessor :authority
def authority
@authority ||= 'localhost:80'
end
# Here's the callback majick!
def get(path = '/', callbacks = HTTPartyHarder::Callbacks.new)
begin
response = self.class.get( File.join('http://', @authority, path) )
callbacks[:complete].call(response)
# you could also check for a status code here...
response
# URI::InvalidURIError, SocketError, Errno::ECONNREFUSED
rescue Exception => error
callbacks[:error].call(error)
nil
end
end
# Oh, the joys of dependency injection
class Callbacks < Hash
def initialize(params = {})
self[:complete] = lambda {|response|}
self[:error] = lambda {|error|}
# You could also set these up ...
self[:success] = lambda {|response|}
self[:failure] = lambda {|response|}
end
end
end
class Peer
include HTTParty
include HTTPartyHarder
# This kinda sucks
def initialize(authority = nil)
@authority = authority if authority
end
end
@coworker = Peer.new('me:pass@127.0.0.1:80')
puts @coworker.authority
@coworker.get('your-mom', {
:error => lambda {|error| p "Rats! #{error}"},
:complete => lambda {|response| p "Woohoo! #{response.headers['status']}"}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment