Jon-Michael Deldin

BMX, bike trials, & software from the Pacific Northwest

Ruby URI.join Gotcha

Quick tip: Don’t be dumb and assume Ruby’s URI.join is like Array.join. I made a seemingly innocent change to add some new functionality to an old API:

URI.join("http://example.com", "/admin/important_base", "/some_endpoint_argument")

I expected this:

http://example.com/admin/important_base/some_endpoint_argument

but I got this instead:

http://example.com/admin/some_endpoint_argument

Options

File.join gives the closest functionality, as far as handling as slashes intelligently:

File.join("http://example.com", "/admin/important_base/", "/some_endpoint_argument")
#=> "http://example.com/admin/important_base/some_endpoint_argument"
URI(_)
#=> #<URI::HTTP http://example.com/admin/important_base/some_endpoint_argument>

The other obvious candidates – Array.join or string concatenation – require managing forward-slashes, which is what I was hoping to avoid in the first place.

* * *