0

I have HTML documents that contain image tags . I need to pick out each image tag's source attribute and specify a full path instead of the relative path already present . That is to append the absolute path .

Current Version :

<img src = '/assets/rails.png' />

After transformation :

<img src = 'http://localhost:3000/assets/rails.png' />

What would be the cleanest and most efficient way to do this in RoR ?

Addition

I am going to use the transformed HTML as a string and pass it to IMgKit gem for transformation into an image .

Superq
  • 153
  • 3
  • 16
  • Please check also http://stackoverflow.com/questions/6500025/how-do-i-get-an-absolute-url-for-an-asset-in-rails-3-1 – Galen May 13 '13 at 15:11
  • It's not clear what you want. Are the HTML files HTML templates, or are they real HTML files that you need to parse and transform the `src` parameters? – the Tin Man May 13 '13 at 15:30

2 Answers2

3

It's hard to figure out if you mean you have HTML templates, such as HAML or ERB, or real HTML files. If you're trying to manipulate HTML files, you should use Nokogiri to parse and change the src parameters:

require 'nokogiri'
require 'uri'

html = '<html><body><img src="/path/to/image1.jpg"><img src="/path/to/image2.jpg"></body></html>'
doc = Nokogiri.HTML(html)

doc.search('img[src]').each do |img|
  img['src'] = URI.join('http://localhost:3000', img['src']).to_s
end

puts doc.to_html

Which outputs:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<img src="http://localhost:3000/path/to/image1.jpg"><img src="http://localhost:3000/path/to/image2.jpg">
</body></html>

You could do the manipulation of the src parameters various ways, but the advantage to using URI, is it's aware of the various twists and turns that URLs need to follow. Rewriting the parameter using gsub or text manipulation requires you to pay attention to all that, and, unexpected encoding problems can creep in.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
0

You can create a helper method so you can use it everywhere

def full_image_path(image)
  request.protocol + request.host_with_port + image.url
end
Anezio Campos
  • 1,555
  • 1
  • 10
  • 18