How do I monkey-patch ruby's URI.parse method

两盒软妹~` 提交于 2020-01-03 08:39:08

问题


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?


回答1:


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



回答2:


@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


来源:https://stackoverflow.com/questions/3891158/how-do-i-monkey-patch-rubys-uri-parse-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!