如何对 ruby​​ 的 URI.parse 方法进行猴子补丁

发布于 2024-09-26 20:05:55 字数 741 浏览 0 评论 0原文

一些流行的博客网站通常在其 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 技术交流群。

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

发布评论

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

评论(2

自此以后,行同陌路 2024-10-03 20:05:55

alias_method_chain 在模块级别执行,因此它只影响实例方法。

您要做的就是在模块的类级别上执行它:

require 'uri'

module URI
  class << self

    def parse_with_safety(uri)
      parse_without_safety uri.gsub('[', '%5B').gsub(']', '%5D')
    end

    alias parse_without_safety parse
    alias parse parse_with_safety
  end
end

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:

require 'uri'

module URI
  class << self

    def parse_with_safety(uri)
      parse_without_safety uri.gsub('[', '%5B').gsub(']', '%5D')
    end

    alias parse_without_safety parse
    alias parse parse_with_safety
  end
end
夏雨凉 2024-10-03 20:05:55

@nil 他的评论非常有帮助,我们最终得到以下结果:

def parse_with_safety(uri)
  begin
    parse_without_safety uri.gsub(/([{}|\^\[\]\@`])/) {|s| URI.escape(s)}
  rescue
    parse_without_safety '/'
  end
end

@nil his comment is very helpful, we ended up with the following:

def parse_with_safety(uri)
  begin
    parse_without_safety uri.gsub(/([{}|\^\[\]\@`])/) {|s| URI.escape(s)}
  rescue
    parse_without_safety '/'
  end
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文