Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monkeypatch Ruby properly?

I'm trying to monkeypatch a line in Net class in the standard library. I created a file called patches.rb into the lib folder of the project and added this

module Net
  class HTTP < Protocol
    module HTTPHeader
      def initialize_http_header(initheader)
        @header = {}
        return unless initheader
        initheader.each do |key, value|
          @header[key.downcase] = [value.strip] rescue ""
        end
      end
    end
  end
end

But it doesn't work. Am I doing this right? (That parallels the inheritance hierarchy exactly.)

Edit: part of the problem was I had to put the file in the initalizers folder. But still seeing the same error.

like image 347
picardo Avatar asked May 10 '11 19:05

picardo


1 Answers

Since things in the lib/ directory are only loaded on demand, you may have more success putting patches like this in config/initializers/ where they are automatically loaded after the stack has been initialized.

You can also collapse the definition for extensions to something like this:

module Net::HTTP::HTTPHeader
  # ... (redefined methods) ...
end
like image 110
tadman Avatar answered Oct 27 '22 06:10

tadman