允许主机名含有下划线的 URI.parse 替代方案

6
我是使用DMOZ网址主题列表,其中包含一些主机名包含下划线的url。
例如:
608  <ExternalPage about="http://outer_heaven4.tripod.com/index2.htm">
609    <d:Title>The Outer Heaven</d:Title>
610    <d:Description>Information and image gallery of McFarlane's action figures for Trigun, Akira, Tenchi Muyo and other Japanese Sci-Fi animations.</d:Description>
611    <topic>Top/Arts/Animation/Anime/Collectibles/Models_and_Figures/Action_Figures</topic>
612  </ExternalPage>

虽然这个URL在Web浏览器中能够使用(至少在我的浏览器中是可以的:p),但是根据标准,它是不合法的:

主机名不能包含其他字符,比如下划线(_)等,

如果尝试使用 URI.parse 解析这样的URL会出现错误:

[2] pry(main)> require 'uri'
=> true
[3] pry(main)> URI.parse "http://outer_heaven4.tripod.com/index2.htm"
URI::InvalidURIError: the scheme http does not accept registry part: outer_heaven4.tripod.com (or bad hostname?)
from ~/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/uri/generic.rb:213:in `initialize'

有没有其他的替代方法可以代替 URI.parse,并且更加宽松一些,而不是自己编写代码?

1个回答

11

试试Addressable::URI。它比URI更严格地遵循RFC,并且非常灵活。

require 'addressable/uri'
uri = Addressable::URI.parse('http://outer_heaven4.tripod.com/index2.htm') 
uri.host 
=> "outer_heaven4.tripod.com"

我已经在一些项目中使用过它并感到很满意。URI有点...生锈,需要精心呵护。其他人也评论了它:

http://www.cloudspace.com/blog/2009/05/26/replacing-rubys-uri-with-addressable/

几年前,Ruby开发者之间曾对URI的状态进行过相当大的讨论。我现在找不到链接了,但是有一个建议使用Addressable::URI作为替代品。我不知道是否有人接手了URI的开发工作,或者现在情况如何。在我的代码中,我继续使用URI处理简单的事情,并在URI无法胜任时切换到Addressable::URI。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接