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

拈花ヽ惹草 提交于 2019-12-04 18:27:25

问题


Given any valid HTTP/HTTPS string, I would like to parse/transform it such that the end result is exactly the root of the string.

So given URLs:

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

I would like the results:

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

I found the documentation for URI::Parser not super approachable.

My initial, naïve solution would be a simple regex like:

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

(That is: Match up to the first slash after the protocol.)

Thoughts & solutions welcome. And apologies if this is a duplicate, but my search results weren't relevant.


回答1:


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



回答2:


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.




回答3:


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"


来源:https://stackoverflow.com/questions/6755919/ruby-rails-3-1-given-a-url-string-remove-path

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