Always adding http_proxy support when using Ruby’s Net:HTTP
Recently there have been a number of times I’ve needed to use Ruby’s Net:HTTP library. Because I develop inside a company firewall, all HTTP traffic has to go through a proxy. This means our libraries always need the Proxy support that Net:HTTP has. This means we now have a common idiom, and here it is:
require 'ostruct' url = URI.parse("http://destination.com") proxy = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : OpenStruct.new conn = Net::HTTP::Proxy(proxy.host, proxy.port).new(url.host, url.port)
Simple! You can use this every time, and your lib will have proxy support based on the http_proxy environment variable being set. If it’s not set, then it will just carry on as expected.