Class: Closure::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/closure/compiler.rb

Overview

The Closure::Compiler is a basic wrapper around the actual JAR. There’s not much to see here.

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :warning_level => 'QUIET',
  :language_in => 'ECMASCRIPT5'
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Compiler

When you create a Compiler, pass in the flags and options.



21
22
23
24
25
# File 'lib/closure/compiler.rb', line 21

def initialize(options={})
  @java     = options.delete(:java)     || JAVA_COMMAND
  @jar      = options.delete(:jar_file) || COMPILER_JAR
  @options  = DEFAULT_OPTIONS.merge(options)
end

Instance Attribute Details

#optionsObject

Returns the value of attribute options.



13
14
15
# File 'lib/closure/compiler.rb', line 13

def options
  @options
end

Instance Method Details

#compile(io) {|StringIO.new(result)| ... } ⇒ Object Also known as: compress

Can compile a JavaScript string or open IO object. Returns the compiled JavaScript as a string or yields an IO object containing the response to a block, for streaming.

Yields:

  • (StringIO.new(result))


30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/closure/compiler.rb', line 30

def compile(io)
  tempfile = Tempfile.new('closure_compiler')
  if io.respond_to? :read
    while buffer = io.read(4096) do
      tempfile.write(buffer)
    end
  else
    tempfile.write(io.to_s)
  end
  tempfile.flush

  begin
    result = compile_files(tempfile.path)
  rescue Exception => e
    raise e
  ensure
    tempfile.close!
  end

  yield(StringIO.new(result)) if block_given?
  result
end

#compile_files(files) {|StringIO.new(result)| ... } ⇒ Object Also known as: compile_file

Takes an array of javascript file paths or a single path. Returns the resulting JavaScript as a string or yields an IO object containing the response to a block, for streaming.

Yields:

  • (StringIO.new(result))


57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/closure/compiler.rb', line 57

def compile_files(files)
  @options.merge!(:js => files)

  begin
    redirect_stderr = "2>&1" if !Gem.win_platform?
    result = `#{command} #{redirect_stderr}`
  rescue Exception
    raise Error, "compression failed: #{result}"
  end

  unless $?.exitstatus.zero?
    raise Error, result
  end

  yield(StringIO.new(result)) if block_given?
  result
end