Last active
February 9, 2016 05:08
-
-
Save msr1k/c763c5967c2dd42bfe0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| module ConvertToStandAloneHTML | |
| EMPTY_LINE = /^\s*$/ | |
| # | |
| # This is the only public method. | |
| # Please use like this. | |
| # | |
| # Pack[ "Some HTML string to be converted." ] | |
| def self.[] contents | |
| image_tag = /<img\s*.*?\s*src="(.*?\.png)".*?>/i | |
| ret = contents.each_line.map do |l| | |
| case l | |
| when /<script\s*.*\s*src="(.*?\.js)".*>/ | |
| "<script type='text/javascript'>#{ File.read( "./#{$1}" ) }</script>" | |
| when /<link\s*.*\s*href="(.*?\.css)".*>/ | |
| css_contents = File.read( "./#{$1}" ) | |
| "<style type='text/css'>#{ source_css_images( css_contents ) }</style>" | |
| when image_tag | |
| puts "SOURCE: #{l}" | |
| l.gsub( image_tag ) do |matched| | |
| data = File.open("./#{$1}", "r" ){ |f| f.binmode.read } | |
| encoded = [data].pack( "m*" ).split("\n").join("") | |
| matched.gsub( /src=".*"/, "src='data:image/png;base64,#{encoded}'" ) | |
| end | |
| when EMPTY_LINE then nil | |
| else l | |
| end rescue l | |
| end.compact.join("\n") | |
| ret | |
| end | |
| def self.source_css_images css_contents | |
| image_url = /^.*:\s*url\(\s*["']images\/(.*?\.png)["']\).*;.*$/ | |
| css_contents.each_line.map do |l| | |
| case l | |
| when image_url | |
| l.gsub( image_url ) do |matched| | |
| data = File.open( Dir.glob( "**/#{$1}" ).first, "r" ){ |f| f.binmode.read } | |
| encoded = [data].pack( "m*" ).split("\n").join("") | |
| matched.gsub( /url\(.*?\)\s*;.*$/, "url(data:image/png;base64,#{encoded});" ) | |
| end | |
| when EMPTY_LINE then nil | |
| else l | |
| end rescue l | |
| end.compact.join("\n") | |
| end | |
| private_class_method :source_css_images | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment