【问题标题】:Ruby/Rails 3.1: Given a URL string, remove pathRuby/Rails 3.1:给定一个 URL 字符串,删除路径
【发布时间】:2011-07-20 01:06:22
【问题描述】:

给定任何有效的 HTTP/HTTPS 字符串,我想对其进行解析/转换,以使最终结果恰好是字符串的根。

所以给定网址:

http://foo.example.com:8080/whatsit/foo.bar?x=y
https://example.net/

我想要结果:

http://foo.example.com:8080/
https://example.net/

我发现 URI::Parser 的 documentation 不是超级平易近人。

我最初的、幼稚的解决方案是一个简单的正则表达式,例如:

/\A(https?:\/\/[^\/]+\/)/

(即:匹配到协议后的第一个斜线。)

欢迎提出想法和解决方案。如果这是重复的,请道歉,但我的搜索结果不相关。

【问题讨论】:

  • 为了避免有人试图使用我上面的天真的“解决方案”——请注意,当没有路径时,它无法匹配省略尾部斜杠的 URL,即 http://example.com 而不是 @987654326 @.

标签: ruby-on-rails ruby ruby-on-rails-3.1


【解决方案1】:

与URI::join:

require 'uri'
url = "http://foo.example.com:8080/whatsit/foo.bar?x=y"
baseurl = URI.join(url, "/").to_s
#=> "http://foo.example.com:8080/"

【讨论】:

  • 我真的很喜欢这个答案。事后看来,这似乎很明显。 URI.join 是最好的!谢谢!
【解决方案2】:

使用URI.parse,然后将path设置为空字符串,将query设置为nil:

require 'uri'
uri     = URI.parse('http://foo.example.com:8080/whatsit/foo.bar?x=y')
uri.path  = ''
uri.query = nil
cleaned   = uri.to_s # http://foo.example.com:8080

现在您在cleaned 中获得了清理后的版本。有时,取出你不想要的东西比只抓住你需要的东西更容易。

如果你只使用uri.query = '',你最终会得到http://foo.example.com:8080?,这可能不是你想要的。

【讨论】:

  • 并检查URI#split 以获取您可能想要清除(或不清除)的其他类型的信息,例如用户信息,片段,...
【解决方案3】:

您可以使用uri.split(),然后将部件重新组合在一起...

警告:这有点草率。

url = "http://example.com:9001/over-nine-thousand"
parts = uri.split(url)
puts "%s://%s:%s" % [parts[0], parts[2], parts[3]]

=> "http://example.com:9001"

【讨论】:

  • 嗯,好的,我也可以包含端口。 Documentation here
  • URL 中也可能有用户信息。是的,我知道,我对病理病例很挑剔:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-03
  • 2017-09-21
  • 1970-01-01
  • 2023-03-30
  • 2019-03-04
相关资源
最近更新 更多