Ruby Script to Localise Images for Offline HTML

I’m maintaining a custom HTML5 slide framework. A little similar to the canonical slides.html5rocks.com insofar as, well, it’s HTML5 and slides horizontally! But the key difference is that it’s very markup-based – What You See Is What You Need (WYSIWYN) – so creating new slides is easy.

Anyway, I did something similar with TiddlySlides a little while ago, and @FND created a nice Python script to inline external resources – http://mini.softwareas.com/using-fnds-excellent-spapy-to-make-a-single-p. I wanted something slightly different; since this is markup, I can’t rely on <img src… pattern. Could have possibly incorporated changes into Fred’s SPA, but being that I need it for GDC presentation tomorrow, and I said the last thing to myself the last time I did these slides and it didn’t happen, I opted to make a Ruby script which is general-purpose, but meets the specific needs of my slides. See GIST

  1. #!/usr/bin/env ruby
  2. # This script will download all images referenced in URL (URLs ending in
  3. # jpg/gif/png), stick them in an images/ directory if they're not already there,
  4. # and make a new file referencing the local directory.
  5. #
  6. # The script depends on the http://github.com/nahi/httpclient library.
  7. #
  8. # USAGE
  9. # localiseImages.rb index.html
  10. # ... will create images/ containing images and local.index.html pointing to them.
  11. #
  12. # The point is to cache images so your HTML works offline. See also spa.py
  13. # http://mini.softwareas.com/using-fnds-excellent-spapy-to-make-a-single-p
  14.  
  15. require 'httpclient'
  16.  
  17. ### UTILITIES
  18. IMAGES_DIR = 'images'
  19. Dir.mkdir(IMAGES_DIR) unless File.directory?(IMAGES_DIR)
  20. def filenameize(url)
  21.   IMAGES_DIR + '/' + url.sub('http://','').gsub('/','__')
  22. end
  23.  
  24. def save(filename,contents)
  25.   file = File.new(filename, "w")
  26.   file.write(contents)
  27.   file.close
  28. end
  29.  
  30. ### CORE
  31. def saveImage(url)
  32.   save(filenameize(url), HTTPClient.new().get_content(url))
  33. end
  34.  
  35. def extractImages(filename)
  36.   contents = File.open(filename, "rb").read
  37.   localContents = String.new(contents)
  38.   contents.scan(/http://S+?.(?:jpg|gif|png)/im) { |url|
  39.     puts url
  40.     saveImage(url) unless File.file?(filenameize(url))
  41.     localContents.gsub!(url, filenameize(url))
  42.   }
  43.   save("local."+filename, localContents)
  44. end
  45.  
  46. ### COMMAND-LINE
  47. extractImages(ARGV[0])

Aside: This is also related to “offline” web technologies…my article on “Offline” recently went live at HTML5Rocks: “Offline”: What does it mean and why should I care?.

One thought on “Ruby Script to Localise Images for Offline HTML

Leave a Reply