Alex Rivera | Logout

How do I safely join relative url segments?

Asked 2012-01-17T19:49:53.547
43

I'm trying to find a robust method of joining partial url path segments together. Is there a quick way to do this?

I tried the following:

puts URI::join('resource/', '/edit', '12?option=test')

I expect:

resource/edit/12?option=test

But I get the error:

`merge': both URI are relative (URI::BadURIError)

I have used File.join() in the past for this but something does not seem right about using the file library for urls.

Edit
Report

1 Answer

8

The problem is that resource/ is relative to the current directory, but /edit refers to the top level directory due to the leading slash. It's impossible to join the two directories without already knowing for certain that edit contains resource.

If you're looking for purely string operations, simply remove the leading or trailing slashes from all parts, then join them with / as the glue.

answered 2012-01-17T19:53:21.237

Your Answer