Skip to content

Commit

Permalink
fully support user options, more specs
Browse files Browse the repository at this point in the history
  • Loading branch information
sam0x17 committed Nov 2, 2019
1 parent 03595b2 commit cb7d1bb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 3 deletions.
21 changes: 21 additions & 0 deletions spec/html-minifier_spec.cr
Expand Up @@ -17,4 +17,25 @@ describe HtmlMinifier do
result = "<html><head><script>function foo(){return 0}</script></head></html>"
HtmlMinifier.minify!(html).should eq result
end

it "handles newlines" do
html = <<-HTML
<html>
<body>test</body>
</html>
HTML
HtmlMinifier.minify!(html).should eq " <html> <body>test</body> </html>"
end

it "handles double quotes" do
html = "<html><div class=\"thing\"></div></html>"
result = "<html><div class=\"thing\"></div></html>"
HtmlMinifier.minify!(html).should eq result
end

it "allows user-specified options" do
HtmlMinifier.minify!("<html><!-- comment --></html>").should eq "<html></html>"
HtmlMinifier.set_options("{\"removeComments\":false}")
HtmlMinifier.minify!("<html><!-- comment --></html>").should eq "<html><!-- comment --></html>"
end
end
20 changes: 17 additions & 3 deletions src/html-minifier.cr
@@ -1,4 +1,5 @@
require "duktape"
require "json"

HTML_MINIFIER_JS = {{read_file("html-minifier/html-minifier.min.js")}}

Expand All @@ -17,12 +18,18 @@ DEFAULT_OPTIONS = <<-JS
}
JS


module HtmlMinifier
def self.initialize_context
def self.initialize_context(options_json : String? = nil)
ctx = Duktape::Sandbox.new
ctx.eval!(HTML_MINIFIER_JS)
ctx.eval!(DEFAULT_OPTIONS)
if options_json
options_json = options_json.not_nil!
options_json = options_json.gsub("\"", "\\\"")
options_json = options_json.gsub("\n", "\\n")
ctx.eval!("var user_options = JSON.parse(\"#{options_json}\")")
ctx.eval!("for(var key in user_options) options[key] = user_options[key];")
end
ctx.eval!("var minify = require('html-minifier').minify;")
ctx
end
Expand All @@ -31,11 +38,18 @@ module HtmlMinifier
def self.minify!(source : String)
@@ctx ||= initialize_context
ctx = @@ctx.not_nil!
source = source.gsub("\"", "\\\"")
source = source.gsub("\n", "\\n")
source = source.gsub("'", "\\'")
ctx.eval!("var output = minify(\'#{source}\', options);")
ctx.eval!("output")
ctx.get_string(-1).not_nil!
end

def self.set_options(options : String)
@@ctx = initialize_context(options)
end

def self.set_options(options : JSON::Any)
@@ctx = initialize_context(options.to_json)
end
end

0 comments on commit cb7d1bb

Please sign in to comment.