TIL: Debugging Net::HTTP
Today I had to debug a library to try and determine why a particular HTTP request was failing. The problem was, this particular library uses Net::HTTP, without any particular hooks to customise how the request will be executed.
I discovered the following handy code snippet at https://gist.github.com/ahoward/736721, which forces debug output to be on for any instance of Net::HTTP created. This snippet can be pasted into an initializer or even an IRB/pry debugging session to enable debug logging of Net::HTTP to STDERR:
BEGIN {
require 'net/http'
Net::HTTP.module_eval do
alias_method '__initialize__', 'initialize'
def initialize(*args,&block)
__initialize__(*args, &block)
ensure
@debug_output = $stderr ### if ENV['HTTP_DEBUG']
end
end
}
I wouldn’t recommend this code for any deployed environment, since it’s monkeypatching a pretty core Ruby class. It’s a great debugging tool though, if you’re not too sure how to get to a particular HTTP request.