本文介绍了我如何猴子补丁 ruby​​ 的 URI.parse 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

一些流行的博客站点通常在其 URL 中使用方括号,但 ruby​​ 的内置 URI.parse() 方法会阻塞它们,引发令人讨厌的异常,如下所示:http://redmine.ruby-lang.org/issues/show/1466

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

我正在尝试编写一个简单的猴子补丁,它可以优雅地处理带有方括号的 URL.以下是我目前所拥有的:

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'

/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'

如何成功对 URI.parse 进行猴子补丁?

How can I successfully monkey-patch URI.parse?

推荐答案

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:

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

这篇关于我如何猴子补丁 ruby​​ 的 URI.parse 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 21:19