Skip to content

Instantly share code, notes, and snippets.

@laiso
Created November 14, 2016 14:41
Show Gist options
  • Save laiso/b2515104eae2877a907ccda1bf9b59c1 to your computer and use it in GitHub Desktop.
Save laiso/b2515104eae2877a907ccda1bf9b59c1 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require "open-uri"
class Converter
RE_MD_IMAGE = /\!\[.*\]\((http.+)\)/
RE_TAG_IMAGE = /<img .*src="(http.+?)".+?>/
def initialize(file, conf)
@conf = conf
@source_text = File.read(file)
end
def output
urls = image_urls
image_paths = urls.map do |url|
download(url)
end
text = @source_text
urls.each_with_index do |url, i|
text.gsub!(url, image_paths[i])
end
text
end
def download(url)
resource = open(url)
path = "#{@conf[:download_path]}/#{url.split('/').last}"
File.open(path, 'wb') do |f|
f.write(resource.read)
end
path
end
def image_urls
image_tags = @source_text.scan(RE_TAG_IMAGE)
image_tags.zip(@source_text.scan(RE_MD_IMAGE)).flatten
end
end
if __FILE__==$0
source_file = ARGV[0] || "slide.md"
conv = Converter.new(source_file, {download_path: 'images'})
puts conv.output
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment