Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse url to get base url? -- Rails 3.1

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.

like image 930
user1049097 Avatar asked Nov 27 '11 18:11

user1049097


2 Answers

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
like image 112
WarHog Avatar answered Sep 17 '22 20:09

WarHog


2 alternative ways

uri = URI.parse(url); uri.path = ''; uri.query = nil; uri.to_s
url.split('/')[0,3].join('/')
like image 20
skojin Avatar answered Sep 19 '22 20:09

skojin