Alan H. Alan H. - 4 months ago 26
Ruby Question

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

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.

Answer

Check URI::join:

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