Skip to content

Instantly share code, notes, and snippets.

@jsimnz
Forked from arirusso/img_convert.rb
Created March 8, 2015 21:37
Show Gist options
  • Save jsimnz/5622d60622d526d42ef8 to your computer and use it in GitHub Desktop.
Save jsimnz/5622d60622d526d42ef8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'nokogiri'
require 'uri'
# opens every file in the given dir tree and converts any html img tags to rails image_tag calls
#
# example usage:
# ruby convert.rb ~/my_rails_app/app/views
#
# ***be careful and backup before using this***
#
raise "no directory tree given" if ARGV.first.nil?
path = "#{ARGV.first}/**/*"
@count = {
:files_open => 0,
:files_revised => 0,
:tags => 0
}
class RailsImageTag
def initialize(img)
@img = img
end
# construct and return the erb containing the new image_tag call
def to_erb
uri_parts = URI.parse(@img['src']).path.split('/')
asset_name = ""
if uri_parts[uri_parts.length - 2] != "images"
asset_name = uri_parts[uri_parts.length - 2] + "/" + uri_parts[uri_parts.length - 1]
else
asset_name = uri_parts.last
end
"<%= image_tag('#{asset_name}', #{options_to_erb}) %>"
end
# convert the img tag params to image_tag options
def options_to_erb
@img.attributes.collect{|k,v| "#{k}: '#{v}'" if !v.blank? and k != 'src' }.compact.join(', ')
end
end
class HtmlDoc
def initialize(filename)
@name = filename
file = File.open(@name)
@doc = Nokogiri::HTML(file)
@content = File.open(@name) { |f| f.read }
end
# overwrite the file with new contents
def write_file
puts "writing #{@name}"
File.open(@name, "w") {|f| f.write(@content) }
end
# convert a single file and record stats to <em>log</em>
def convert_img_tags!(log)
log[:files_open] += 1
file_marked = false
@doc.xpath("//img").each do |img|
file_marked = true
log[:tags] += 1
replaced = RailsImageTag.new(img).to_erb
puts "original: #{img.to_s}, replaced: #{replaced}"
@content = @content.gsub(img.to_s, replaced)
#img.replace(replaced)
end
if file_marked
log[:files_revised] += 1
write_file
end
end
end
Dir.glob(path).each { |filename| HtmlDoc.new(filename).convert_img_tags!(@count) if File.file?(filename) }
p "***********************************"
p "#{@count[:files_open]} files opened"
p "#{@count[:files_revised]} files revised"
p "#{@count[:tags]} tags replaced"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment