开发者

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

Input: calico.gif

Result: http://example.com/foo/calico.gif

Complete:  http://example.com/foo/bar.html

Input: ../x.html

Result: http://example.com/x.html

Complete:  http://example.com/foo/bar.html

Input: /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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜