我正在使用 DMOZ的 list of url topics ,其中包含一些具有包含下划线的主机名的 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 可以在网络浏览器中使用(或者至少在我的浏览器中可以使用 :p),it's not legal according to the standard :
a hostname may not contain other characters, such as the underscore character (_),
当尝试使用 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
的替代方案,我可以使用它具有较低的严格性,而无需自己滚动?
最佳答案
尝试 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 有点……生锈了,需要 TLC。其他人也对此发表了评论:
http://www.cloudspace.com/blog/2009/05/26/replacing-rubys-uri-with-addressable/
几年前,Ruby 开发人员就 URI 的状态进行了相当多的讨论。我现在找不到它的链接,但有人建议将 Addressable::URI 用作替代品。我不知道是否有人接管了 URI 开发,或者现在的情况。在我自己的代码中,我继续将 URI 用于简单的事情,并在 URI 证明对我做错事时切换到 Addressable::URI。
关于ruby - 允许主机名包含下划线的 URI.parse 的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13197605/