如何正确地对 Ruby 进行猴子补丁?
我正在尝试对标准库中的 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于
lib/
目录中的内容仅按需加载,因此您可能会更成功地将此类补丁放入config/initializers/
中,在堆栈完成后它们会自动加载已初始化。您还可以将扩展的定义折叠为如下所示:
Since things in the
lib/
directory are only loaded on demand, you may have more success putting patches like this inconfig/initializers/
where they are automatically loaded after the stack has been initialized.You can also collapse the definition for extensions to something like this: