How to parse url to get base url? -- Rails 3.1
Asked Answered
G

3

13

How can I parse urls like

http://www.1800contacts.com/productlist.aspx?dl=P&source=cj&ac=8.2.0007

and only get

http://www.1800contacts.com

?

PS. Some urls have subdomains etc so I can't use regexps here.

Guideline answered 27/11, 2011 at 18:56 Comment(0)
D
26

Try to use 'uri' library:

require 'uri'
address = 'http://www.1800contacts.com/productlist.aspx?dl=P&source=cj&ac=8.2.0007'
uri = URI.parse(address)
puts "#{uri.scheme}://#{uri.host}"  # => http://www.1800contacts.com
Demonolatry answered 27/11, 2011 at 19:1 Comment(2)
Is there a solution to include non-standard ports, such as example.com:8080/you-found-me.php ?Upanddown
Sure. Change address to address = 'http://example.com:8080/you-found-me.php' and it give you following: uri.port # => 8080Demonolatry
H
2

I like @skojin's answer number 1 (sorry I opened another answer, it's only a long comment) because it makes more general code for both cases:

require 'uri'

uri = URI "http://www.1800contacts.com/productlist.aspx?dl=P&source=cj&ac=8.2.0007"
uri.query = uri.fragment = nil
uri.path = ""
uri.to_s
# => "http://www.1800contacts.com"

uri = URI "http://example.com:8080/you-found-me.php"
uri.query = uri.fragment = nil
uri.path = ""
uri.to_s
# => "http://example.com:8080"
Hendecagon answered 20/9, 2018 at 20:12 Comment(0)
D
1

2 alternative ways

uri = URI.parse(url); uri.path = ''; uri.query = nil; uri.to_s
url.split('/')[0,3].join('/')
Dibb answered 26/12, 2013 at 8:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.