Ruby (or Rails): How can I apply a relative URL to a full URL?
Given a complete URL, I need to handle every possible kind of valid relative 开发者_运维技巧URL, like you might see in an HREF attribute on the page at the first location, or in a Location:
header.
Examples:
Complete: http://example.com/foo/bar.html
calico.gif
Result: http://example.com/foo/calico.gif
Complete: http://example.com/foo/bar.html
../x.html
Result: http://example.com/x.html
Complete: http://example.com/foo/bar.html
/robots.txt
Result: http://example.com/robots.txt
Question
How can I reliably handle these sorts of relative URLs? I have to imagine someone has written solid code for this before.
require 'uri'
URI::join("http://domain.com/dir", "/images/small/image.png")
URI::join("http://example.com/foo/bar.html", "calico.gif")
...
and just call .to_s
to get a string.
精彩评论