Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created December 10, 2010 20:06
Show Gist options
  • Star 59 You must be signed in to star a gist
  • Fork 15 You must be signed in to fork a gist
  • Save ahoward/736721 to your computer and use it in GitHub Desktop.
Save ahoward/736721 to your computer and use it in GitHub Desktop.
a simple way to debug tons of libs that use ruby's net/http
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
}
@AndrewVos
Copy link

Couldn't you remove line 6 and replace line 9 with "super"?

@drogus
Copy link

drogus commented Dec 13, 2010

AndrewVos: no, cause he is changing class definition. He could call super if he would create a new class:

class MyHTTP < Net::HTTP
  def initialize(*)
    super
  ensure
    @debug_output = $stderr
  end
end

@AndrewVos
Copy link

Interesting. First time I've seen BEGIN before, and googling it was kind of tricky :) (did get it eventually though).

@AndrewVos
Copy link

Ok. I actually thought that super would call the same method on the parent class!

I expected this kind of thing to work:

def method_override
  super
end

@drogus
Copy link

drogus commented Dec 18, 2010

AndrewVos: you're right, super will call method from parent class. But in that gist inheritance is not used, class is evaled.

@AndrewVos
Copy link

Ok I get it I think. why couldn't it be written like this though?

require 'net/http'

class Net::HTTP
  def initialize(*args,&block)
    super
  ensure
    @debug_output = $stderr ### if ENV['HTTP_DEBUG']
  end
end

Is it because Net:HTTP is actually a module and not a class?

@myronmarston
Copy link

@AndrewVos: the code you've posted overrides Net::HTTP#initialize and supers to the definition of initialize in Net::HTTP's superclass. This means it totally skips Net::HTTP's own definition of initialize. That's not what you want to do :(.

@troelskn
Copy link

Why module_eval? Isn't this exactly the same, and (imho) much more readable?

module Net
  class HTTP
    alias_method '__initialize__', 'initialize'

    def initialize(*args,&block)
      __initialize__(*args, &block)
    ensure
      @debug_output = $stderr ### if ENV['HTTP_DEBUG']
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment