使用红宝石 1.9.2-p290。我在尝试解析 URI 时遇到了一个问题,如下所示:
require 'uri'
my_uri = "http://www.anyserver.com/getdata?anyparameter={330C-B5A2}"
the_uri = URI.parse(my_uri)
发出以下错误:
URI::InvalidURIError: bad URI(is not URI?)
我需要一个不同的解决方案,而不是每次像这样编码花括号:
new_uri = URI.encode("http://www.anyserver.com/getdata?anyparameter={330C-B5A2}")
=> "http://www.anyserver.com/getdata?anyparameter=%7B330C-B5A2%7D"
现在我可以像往常一样解析 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
现在我可以将 URI.parse(uri) 与包含大括号的 uri 一起使用,并且不会引发错误。