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
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
# File 'lib/yui/compressor.rb', line 85 def compress(stream_or_string) streamify(stream_or_string) do |stream| tempfile = Tempfile.new('yui_compress') tempfile.write stream.read tempfile.flush full_command = "%s %s" % [command, tempfile.path] begin output = `#{full_command}` rescue Exception => e # windows shells tend to blow up here when the command fails raise RuntimeError, "compression failed: %s" % e. ensure tempfile.close! end if $?.exitstatus.zero? output else # Bourne shells tend to blow up here when the command fails, usually # because java is missing raise RuntimeError, "Command '%s' returned non-zero exit status" % full_command end end end |