-1

I have a HTML string, for example,

<html>
  <body>
    <a href="/image/myimage.png"/>
  </body>
</html>

How to convert all relative path into absolute path, like this?

<html>
  <body>
    <a href="http://example.com/image/myimage.png"/>
  </body>
</html>

I am using Ruby on Rails, any suitable gem? Or a general way to do it.

Thanks.

VHanded
  • 2,079
  • 4
  • 30
  • 55

2 Answers2

0

This is a JS function I got some time ago, not really mine and don't remember where I found it (had it as a snippet, so credits to whoever wrote it) but it really works wonders:

var absolutePath = function(href) {
    var link = document.createElement("a");
    link.href = href;
    return (link.protocol+"//"+link.host+link.pathname+link.search+link.hash);
}

EDIT: looking for the author of the above snippet, found a Ruby version for you:

[code = ruby]
Class String
  @@base = "http://example.com"
  def to_link
    "#{@@base}/folder/#{to_s}"
  end
  def to_js
    "#{@@base}/#{to_s}"
  end
end
[/code]

then puts "<a href = #{'link.html'.to_link}>some link</a>"

From Rails Forum

Devin
  • 7,690
  • 6
  • 39
  • 54
0

URL

You'll likely be looking for the _url helpers.

The difference between the _path and _url helpers is the _url helpers will load the absolute path, whereas _path will be relative to your current URL. Here's a great resource:

*_path are for views because ahrefs are implicitly linked to the current URL. So it’d be a waste of bytes to repeat it over and over. In the controller, though, *_url is needed for redirect_to because the HTTP specification mandates that the Location: header in 3xx redirects is a complete URL.

This means, judging from your question, that you'll be best suited to changing any of your _path references to _url:

<%= link_to "", image_url("myimage.png") %>
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147