Just a small pattern is use all the time for writing HTTP requests that work
with an without a proxy.
#!/usr/bin/env ruby require 'net/http' require 'ostruct' proxy = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : OpenStruct.new Net::HTTP::Proxy(proxy.host,proxy.port,proxy.user,proxy.password).start('www.apple.com') do |http| puts http.get('/').body end
I use here the OpenStruct class which actually works like a more generic Struct where fields can added at will. Comes quite handy since You normally want to have “host”, “port”, “username” and “password” accessors for your proxy URL and Net::HTTP::Proxy is kind enough to accept nil values if they are not required :)
Do you want to give me feedback about this article in private? Please send it to comments@zerokspot.com.
Alternatively, this website also supports Webmentions. If you write a post on a blog that supports this technique, I should get notified about your link π