Skip to content

Instantly share code, notes, and snippets.

@mahemoff
Created June 2, 2011 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahemoff/1004612 to your computer and use it in GitHub Desktop.
Save mahemoff/1004612 to your computer and use it in GitHub Desktop.
replace image urls with images
#!/usr/bin/env ruby
# suck.rb index.html will build a local.index.html with all images offline
require 'httpclient'
### UTILITIES
Dir.mkdir('images') unless File.directory?('images')
def imagepath(url)
'images/' + url.sub('http://','').gsub('/','__')
end
def save(filename,contents)
file = File.new(filename, "w")
file.write(contents)
file.close
end
def extractImages(filename)
file = File.open(filename, "rb")
contents = file.read
localContents = String.new(contents)
contents.scan(/http:\/\/\S+?\.(?:jpg|gif|png)/im) { |url|
print '.'
save(imagepath(url), HTTPClient.new().get_content(url)) unless File.exists?(imagepath(url))
localContents.gsub!(url, imagepath(url))
}
puts ''
save("local."+filename, localContents)
end
### COMMAND-LINE
extractImages(ARGV[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment