Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Evaluate a potential relative URI in the context of another in Ruby

Tags:

url

uri

ruby

I have two URIs in a Ruby program. One is for sure an absolute URI and the other might be absolute or relative. I'd like to turn the second one in an absolute URI in the context of the first one, so if the first one is http://pupeno.com/blog and the second is /about, the result should be http://pupeno.com/about. Any ideas how to do it?

like image 583
pupeno Avatar asked Apr 19 '11 17:04

pupeno


2 Answers

Both Ruby's built-in URI, and the Addressable gem, make short work of this. I prefer Addressable because it's more full-featured but URI is built-in.

require 'uri'

URI.join('http://pupeno.com/blog', '/about') # => #<URI::HTTP:0x00000101098538 URL:http://pupeno.com/about>

or

require 'addressable/uri'

uri = Addressable::URI.parse('http://pupeno.com/blog')
uri.join('/about') # => #<Addressable::URI:0x806704a0 URI:http://pupeno.com/about>

It's a good idea to use the join methods supplied, because they do some sanity checking to make sure that the returned address is sane. Directly assigning to the path might break things if you have a relative URL and simply replace the old path. join will take that into account and will replace or merge, whichever is appropriate.

like image 127
the Tin Man Avatar answered Oct 19 '22 17:10

the Tin Man


This will do it:

require 'uri'
url=URI.parse('http://pupeno.com/blog')
=> #<URI::HTTP:0x00000100e35368 URL:http://pupeno.com/blog> 
ruby-1.9.2-p0 > url.path="/about"
=> "/about" 
ruby-1.9.2-p0 > url
=> #<URI::HTTP:0x00000100e35368 URL:http://pupeno.com/about> 
like image 41
eggie5 Avatar answered Oct 19 '22 15:10

eggie5