Ruby on Rails Snippet for Changing Relative Paths to Absolute

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.

One reply on “Ruby on Rails Snippet for Changing Relative Paths to Absolute”

  1. 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]}

Comments are closed.