maletor maletor - 5 months ago 62
Ruby Question

Use Nokogiri to replace <img src /> tags with <%= image_tag %>?

How can I use nokogiri to replace all img tags with image tags? This is to utilize Rails' ability to plugin the correct asset server automatically?

require 'nokogiri'

class ToImageTag

def self.convert
Dir.glob("app/views/**/*").each do |filename|
doc = Nokogiri::HTML(
doc.xpath("//img").each |img_tags|
# grab the src and all the attributes and move them to ERB

# rewrite the file

rescue => err
puts "Exception: #{err}"



Somewhat inspired by maerics' response, I've created a script that does this. It doesn't have an issue with HTML entities because it only uses the nokogiri output as a guide for replacement. The actual replacement is done by using String#gsub!