如何在Ruby中将方案设置为URI对象

maz*_*maz 15 ruby url uri

我正在尝试从用户输入中解析URI.我假设一些用户不会将该方案放在他们的URI中,我想默认为"http".

以下代码不起作用:

require 'uri'   

uri_to_check = URI::parse("www.google.com")
uri_to_check.scheme = "http" unless uri_to_check.scheme

puts uri_to_check.to_s
Run Code Online (Sandbox Code Playgroud)

我希望看到" http://www.google.com ",但我会收到"http:www.google.com".甚至可以这样做吗?

如果是这样,我错过了什么?

有一个更好的方法吗?

the*_*Man 15

前导斜杠(//)表示URL是基于IP的地址,需要标记主机名,以便URI可以正确解析它们.

维基百科有一些很好的概述和使用示例:

http://en.wikipedia.org/wiki/Url, http://en.wikipedia.org/wiki/URI_scheme, http://en.wikipedia.org/wiki/URL_normalization

最佳信息在规范本身:http://www.ietf.org/rfc/rfc1738.txt,特别是3.1节"3.1.通用Internet方案语法".

您可能需要考虑使用Addressable gem.它更聪明,是我在需要进行大量URI解析或操作时使用的.

http://addressable.rubyforge.org/http://addressable.rubyforge.org/api/Addressable/URI.html

  • +1.对于您的特定用例,您可能希望查看`Addressable :: URI.heuristic_parse`,它是*具体*用于该情况,其中某些信息确实从URI中丢失而不是故意遗漏. (10认同)

Sco*_*tus 5

当您要解析的字符串不符合方案时,URI不会将其识别为主机名:

irb(main):001:0> require 'uri'
=> true
irb(main):002:0> uri = URI::parse("www.google.com")
=> #<URI::Generic:0x11cfc88 URL:www.google.com>
irb(main):003:0> uri.path
=> "www.google.com"
irb(main):004:0> uri.host
=> nil
Run Code Online (Sandbox Code Playgroud)

当您在示例中设置方案时,然后调用to_sURI是在没有主机的情况下构建...

您可以尝试以下内容:(这是一个快速的黑客,我不知道URI细节...)

uri = URI::parse("www.google.com")
if uri.scheme.nil? && uri.host.nil?
  unless uri.path.nil?
    uri.scheme = "http"
    uri.host = uri.path
    uri.path = ""
  end
end

puts uri.to_s
Run Code Online (Sandbox Code Playgroud)