Method: YUI::Compressor#compress

Defined in:
lib/yui/compressor.rb

#compress(stream_or_string) ⇒ Object

Compress a stream or string of code with YUI Compressor. (A stream is any object that responds to read and close like an IO.) If a block is given, you can read the compressed code from the block’s argument. Otherwise, compress returns a string of compressed code.

Example: Compress CSS

compressor = YUI::CssCompressor.new
compressor.compress("  div.error {\n    color: red;\n  }\n  div.warning {\n    display: none;\n  }\n")
# => "div.error{color:red;}div.warning{display:none;}"

Example: Compress JavaScript

compressor = YUI::JavaScriptCompressor.new
compressor.compress('(function () { var foo = {}; foo["bar"] = "baz"; })()')
# => "(function(){var foo={};foo.bar=\"baz\"})();"

Example: Compress and gzip a file on disk

File.open("my.js", "r") do |source|
  Zlib::GzipWriter.open("my.js.gz", "w") do |gzip|
    compressor.compress(source) do |compressed|
      while buffer = compressed.read(4096)
        gzip.write(buffer)
      end
    end
  end
end


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/yui/compressor.rb', line 65

def compress(stream_or_string)
  streamify(stream_or_string) do |stream|
    output = true
    status = POpen4.popen4(command, "b") do |stdout, stderr, stdin, pid|
      begin
        stdin.binmode
        transfer(stream, stdin)

        if block_given?
          yield stdout
        else
          output = stdout.read
        end

      rescue Exception => e
        raise RuntimeError, "compression failed"
      end
    end

    if status.exitstatus.zero?
      output
    else
      raise RuntimeError, "compression failed"
    end
  end
end