使用ruby 1.9.2-p290.我遇到了一个试图解析如下URI的问题:
require 'uri'
my_uri = "http://www.anyserver.com/getdata?anyparameter={330C-B5A2}"
the_uri = URI.parse(my_uri)
Run Code Online (Sandbox Code Playgroud)
发出以下错误:
URI::InvalidURIError: bad URI(is not URI?)
Run Code Online (Sandbox Code Playgroud)
我需要一个不同的解决方案,而不是像每次这样编码花括号:
new_uri = URI.encode("http://www.anyserver.com/getdata?anyparameter={330C-B5A2}")
=> "http://www.anyserver.com/getdata?anyparameter=%7B330C-B5A2%7D"
Run Code Online (Sandbox Code Playgroud)
现在我可以照常解析new_uri,但每次需要时都必须这样做.没有每次都这样做,最简单的方法是什么?
我发布了自己的解决方案,因为我没有看到这一点,因为我解决了它.
# Accepts URIs when they contain curly braces
# This overrides the DEFAULT_PARSER with the UNRESERVED key, including '{' and '}'
module URI
def self.parse(uri)
URI::Parser.new(:UNRESERVED => URI::REGEXP::PATTERN::UNRESERVED + "\{\}").parse(uri)
end
end
Run Code Online (Sandbox Code Playgroud)
现在我可以使用带有花括号的uri的URI.parse(uri),并且不会抛出任何错误.