Skip to content

Instantly share code, notes, and snippets.

@gilles
Created January 25, 2011 22:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gilles/795861 to your computer and use it in GitHub Desktop.
Save gilles/795861 to your computer and use it in GitHub Desktop.
monkey patch to use options in koala requests: timeout and proxy
#monkey patch to get timeout, it's a bit cleaner to define a module and use .send (I think)
module PatchedNetHTTPService
def self.included(base)
base.extend ClassMethods
base.class_eval do
class << self
alias_method_chain :make_request, :timeout
end
end
end
module ClassMethods
def make_request_with_timeout(path, args, verb, options = {})
options.merge!(:timeout => 5)
# We translate args to a valid query string. If post is specified,
# we send a POST request to the given path with the given arguments.
# by default, we use SSL only for private requests
# this makes public requests faster
private_request = args["access_token"] || @always_use_ssl || options[:use_ssl]
# if the verb isn't get or post, send it as a post argument
args.merge!({:method => verb}) && verb = "post" if verb != "get" && verb != "post"
server = options[:rest_api] ? Koala::Facebook::REST_SERVER : Koala::Facebook::GRAPH_SERVER
http = create_http(server, private_request, options)
http.use_ssl = true if private_request
# we turn off certificate validation to avoid the
# "warning: peer certificate won't be verified in this SSL session" warning
# not sure if this is the right way to handle it
# see http://redcorundum.blogspot.com/2008/03/ssl-certificates-and-nethttps.html
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
result = http.start do |http|
response, body = if verb == "post"
if params_require_multipart? args
http.request Net::HTTP::Post::Multipart.new path, encode_multipart_params(args)
else
http.post(path, encode_params(args))
end
else
http.get("#{path}?#{encode_params(args)}")
end
Koala::Response.new(response.code.to_i, body, response)
end
end
def create_http(server, private_request, options)
if options[:proxy]
proxy = URI.parse(options[:proxy])
http = Net::HTTP.new(server, private_request ? 443 : nil,
proxy.host, proxy.port, proxy.user, proxy.password)
else
http = Net::HTTP.new(server, private_request ? 443 : nil)
end
if options[:timeout]
http.open_timeout = options[:timeout]
http.read_timeout = options[:timeout]
end
http
end
end
end
#not Koala::NetHTTPService as it is included in Koala
Koala.send :include, PatchedNetHTTPService
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment