Class: HtmlMinifier::Minifier

Inherits:
Object
  • Object
show all
Defined in:
lib/html_minifier/minifier.rb

Constant Summary collapse

Error =
ExecJS::Error
SourceBasePath =
File.expand_path("../../js/", __FILE__)

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ Minifier

Returns a new instance of Minifier.



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/html_minifier/minifier.rb', line 13

def initialize(options = nil)
  if options.instance_of? Hash then
    @options = options.dup
    @log = @options.delete :log
  elsif options.nil?
    @options = nil
  else
    raise 'Unsupported option for HtmlMinifier: ' + options.to_s
  end

  js = %w{console htmlparser htmllint htmlminifier}.map do |i|
    File.open("#{SourceBasePath}/#{i}.js", "r:UTF-8").read
  end.join("\n")
  js = "function globe(){#{js};return this};var global = new globe();"
  @context = ExecJS.compile(js)
end

Instance Method Details

#minify(source) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/html_minifier/minifier.rb', line 30

def minify(source)
  source = source.respond_to?(:read) ? source.read : source.to_s
  js = []
  if @options.nil? then
    js << "var min = global.minify(#{MultiJson.dump(source)});"
  else
    js << "var min = global.minify(#{MultiJson.dump(source)}, #{MultiJson.dump(@options)});"
  end
  js << "return {min:min, logs:global.console.clear()};"

  result = @context.exec js.join("\n")
  if @log.respond_to?(:info)
    result["logs"].each do |i|
      @log.info i
    end
  end
  result["min"]
end