Ruby on Rails Snippet for Changing Relative Paths to Absolute
8 Jul 2008 in Programming, Ruby on Rails by GarrickIf 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.
Comments (1 Comment)
vague added these pithy words on Jul 25 08 at 6:47 amYou 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]}
Add a Comment
Related Entries
- Ruby on Rails is Agile Web Development
- My Rails-based Wiki Engine now in GitHub
- all this work on command line Ruby apps has got me happily avoiding /views
- Using Names in Rails Routes Instead of IDs
- How To Deploy Rails with SVN and Capistrano to a Secondary Domain on TextDrive