如何对 ruby 的 URI.parse 方法进行猴子补丁
一些流行的博客网站通常在其 URL 中使用方括号,但 ruby 的内置 URI.parse() 方法会阻塞它们,引发令人讨厌的异常,如下所示: http://redmine.ruby-lang.org/issues/show/1466
我正在尝试编写一个简单的猴子补丁,可以优雅地处理带有方括号的 URL。以下是我到目前为止所得到的:
require 'uri'
module URI
def self.parse_with_safety(uri)
safe_uri = uri.replace('[', '%5B')
safe_uri = safe_uri.replace(']', '%5D')
URI.parse_without_safety(safe_uri)
end
alias_method_chain :parse, :safety
end
但是运行时,会生成错误:
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext/module/aliasing.rb :33:in alias_method: NameError: 模块“URI”的未定义方法“解析”
如何成功猴子补丁 URI.parse?
Some popular blog sites typically use square brackets in their URLs but ruby's built-in URI.parse() method chokes on them, raising a nasty exception, as per:
http://redmine.ruby-lang.org/issues/show/1466
I'm trying to write a simple monkey-patch that gracefully handles URLs with the square bracket. The following is what I have so far:
require 'uri'
module URI
def self.parse_with_safety(uri)
safe_uri = uri.replace('[', '%5B')
safe_uri = safe_uri.replace(']', '%5D')
URI.parse_without_safety(safe_uri)
end
alias_method_chain :parse, :safety
end
But when run, this generates an error:
/Library/Ruby/Gems/1.8/gems/activesupport-2.3.8/lib/active_support/core_ext/module/aliasing.rb:33:in alias_method: NameError: undefined method 'parse' for module 'URI'
How can I successfully monkey-patch URI.parse?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
alias_method_chain 在模块级别执行,因此它只影响实例方法。
您要做的就是在模块的类级别上执行它:
alias_method_chain is executed on the module level so it only affects instance methods.
What you have to do is execute it on the module's class level:
@nil 他的评论非常有帮助,我们最终得到以下结果:
@nil his comment is very helpful, we ended up with the following: