Created
December 14, 2011 19:56
-
-
Save jch/1478202 to your computer and use it in GitHub Desktop.
make all net/http requests go through an http proxy
This file contains 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 'net/http' | |
module Net | |
module DefaultProxy | |
# Defaults all requests through Net::HTTP through an http proxy. | |
# Example: | |
# require 'net/http' | |
# require 'net/http_extensions' | |
# Net::HTTP.set_http_proxy! | |
# | |
# @param options [Hash] proxy options. | |
# Defaults to parsed values of ENV['http_proxy'] or ENV['HTTP_PROXY'] | |
# :host | |
# :port [Integer] | |
# :user | |
# :password | |
def set_http_proxy!(options = {}) | |
require 'addressable/uri' | |
proxy_uri = if options.empty? | |
Addressable::URI.parse(ENV['HTTP_PROXY'] || ENV['http_proxy']) | |
else | |
require 'ostruct' | |
OpenStruct.new(options) | |
end | |
self.class_eval <<-CODE | |
class << self | |
alias_method :old_new, :new | |
def new(address, port = nil, p_addr = '#{proxy_uri.host}', p_port = #{proxy_uri.port}, p_user = '#{proxy_uri.user}', p_pass = '#{proxy_uri.password}') | |
old_new(address, port, p_addr, p_port, p_user, p_pass) | |
end | |
end | |
CODE | |
end | |
# restore normal net/http behavior | |
def unset_http_proxy! | |
self.class_eval <<-CODE | |
class << self | |
alias_method :new, :old_new | |
end | |
CODE | |
end | |
end | |
end | |
Net::HTTP.extend(Net::DefaultProxy) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment