Skip to content

Instantly share code, notes, and snippets.

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 mewlist/863855 to your computer and use it in GitHub Desktop.
Save mewlist/863855 to your computer and use it in GitHub Desktop.
require 'open-uri'
require 'image_size'
class ConvertAssetInline
def initialize
@orig = nil
@cache = {}
end
def convert(url)
body = crawl(url)
convert_img(body, url)
end
private
def crawl(url, options = {})
open(url) {|f| f.read }.freeze
end
def url_to_data(url)
url = url.to_s
return @cache[url] if @cache[url]
target = open(url) {|f| f.read }.freeze
target_is = ImageSize.new(target)
content_type = "image/#{target_is.get_type.downcase}"
target_b64 = [target].pack('m')
result = "data:#{content_type};base64,#{target_b64}"
@cache[url] = result
result
end
def convert_img(body, base_url)
body.gsub(/<img[^>]*?src=["'](.*?)["']/) { # don't care there are ["'] in the URL
url = URI.join(base_url, $1)
$&.sub($1, url_to_data(url))
}
end
# def convert_favicon ...
# def convert_stylesheets ...
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment