如何正确地对 Ruby 进行猴子补丁?

发布于 2024-11-06 20:12:33 字数 488 浏览 6 评论 0原文

我正在尝试对标准库中的 Net 类中的一行进行猴子修补。我在项目的 lib 文件夹中创建了一个名为 patch.rb 的文件,并添加了这个文件

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

,但它不起作用。我这样做对吗? (这与继承层次结构完全平行。)

编辑:问题的一部分是我必须将文件放在初始化器文件夹中。但仍然看到同样的错误。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

当梦初醒 2024-11-13 20:12:33

由于 lib/ 目录中的内容仅按需加载,因此您可能会更成功地将此类补丁放入 config/initializers/ 中,在堆栈完成后它们会自动加载已初始化。

您还可以将扩展的定义折叠为如下所示:

module Net::HTTP::HTTPHeader
  # ... (redefined methods) ...
end

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文