Ruby/Rails 3.1: Given a URL string, remove path

落花浮王杯 提交于 2019-12-03 13:00:07

With 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/"

Use URI.parse and then set the path to an empty string and the query to 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

Now you have your cleaned up version in cleaned. Taking out what you don't want is sometimes easier than only grabbing what you need.

If you only do uri.query = '' you'll end up with http://foo.example.com:8080? which probably isn't what you want.

You could use uri.split() and then put the parts back together...

WARNING: It's a little sloppy.

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!