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?
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With