Ruby on Rails Snippet for Changing Relative Paths to Absolute

8 Jul 2008 in Programming, Ruby on Rails by Garrick

If you have a bunch of text containing relative path hyperlinks, and you’d like to change to them to absolute paths, you might find this snippet helpful.


content = "some text with a <a href='/path/to/relative_link/'>relative link</a>"
link = "http://somedomain.com/"
content.gsub(/=('|")\//, '=\1*/').gsub(/\*\//, link.match(/(http|https):\/\/[\w.]+\//)[0])

The asterisk ‘*’ is a hackey placeholder for the actual link swapped in with the second gsub. If you know of a way to pass in the link without needing the placeholder, awesome – paste it in the comments. Thanks.


Comment | Trackback URL Short Link: http://grv.me/1500

Comments (1 Comment)

You could use either blocks or string interpolation to get rid of the hacky * thing.

With Interpolation:

content.gsub(/=('|")\//, "=\\1#{link.match(/(http|https):\/\/[\w.]+\//)[0]}./")

With a block:

content.gsub(/=('|")\//) {|m| "=#$1%s/" % link.match(/(http|https):\/\/[\w.]+\//)[0]}

vague added these pithy words on Jul 25 08 at 6:47 am

Add a Comment


XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Related Entries




Creative Commons License
About Sitemap XHTML Sitemap XML
Wordpress theme is a heavily hacked version of "Modicus Remix" by Art Culture. Original by Upstart Blogger