Skip to content

Instantly share code, notes, and snippets.

@milk1000cc
Created December 6, 2011 08:20
Show Gist options
  • Select an option

  • Save milk1000cc/1437342 to your computer and use it in GitHub Desktop.

Select an option

Save milk1000cc/1437342 to your computer and use it in GitHub Desktop.
replace <img src="abc.png" alt="abc"> to <%= image_tag 'abc.png', alt: 'abc' %>
# usage:
# ruby replace_img_to_image_tag_helper.rb [REPLACED_FILE]
require 'nokogiri'
xhtml = true
content = open(ARGV[0]) { |f| f.read }.gsub(/\r\n?/, "\n").gsub("\t", ' ')
doc = Nokogiri::HTML(content)
doc.css('img').each do |img|
attrs = img.attributes
attrs['alt'] ||= ''
src = attrs.delete('src')
args = ["'#{ img['src'].sub(%r!^/?images/!, '') }'"]
args += attrs.map { |k, v| %!#{ k }: '#{ v }'! }
erb = "ERBBEGINESCAPE::::::::= image_tag #{ args * ', ' } ERBENDESCAPE::::::::"
img.swap erb
end
puts doc.send(xhtml ? :to_xhtml : :to_html).
gsub('ERBBEGINESCAPE::::::::', '<%').
gsub('ERBENDESCAPE::::::::', '%>')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment