gat*_*ega 2 ruby parsing uri curly-braces ruby-1.9.2
使用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),并且不会抛出任何错误.
# Need to not fail when uri contains curly braces
# This overrides the DEFAULT_PARSER with the UNRESERVED key, including '{' and '}'
# DEFAULT_PARSER is used everywhere, so its better to override it once
module URI
remove_const :DEFAULT_PARSER
unreserved = REGEXP::PATTERN::UNRESERVED
DEFAULT_PARSER = Parser.new(:UNRESERVED => unreserved + "\{\}")
end
Run Code Online (Sandbox Code Playgroud)
跟进相同的问题,因为DEFAULT_PARSER在任何地方使用,最好完全替换它仅仅用于URI#parse方法.此外,这避免了每次为新Parser对象的实例化分配内存.
| 归档时间: |
|
| 查看次数: |
2015 次 |
| 最近记录: |