2008-01-03 16:05:12 -05:00
|
|
|
require 'zlib'
|
|
|
|
require 'stringio'
|
|
|
|
|
|
|
|
module ActiveSupport
|
2008-03-26 08:27:52 -04:00
|
|
|
# A convenient wrapper for the zlib standard library that allows compression/decompression of strings with gzip.
|
2008-01-03 16:05:12 -05:00
|
|
|
module Gzip
|
|
|
|
class Stream < StringIO
|
2011-02-09 04:23:45 -05:00
|
|
|
def initialize(*)
|
2011-02-09 16:47:32 -05:00
|
|
|
super
|
|
|
|
set_encoding "BINARY" if "".encoding_aware?
|
|
|
|
end
|
2008-01-03 16:05:12 -05:00
|
|
|
def close; rewind; end
|
|
|
|
end
|
|
|
|
|
2008-03-26 08:27:52 -04:00
|
|
|
# Decompresses a gzipped string.
|
2008-01-03 16:05:12 -05:00
|
|
|
def self.decompress(source)
|
|
|
|
Zlib::GzipReader.new(StringIO.new(source)).read
|
|
|
|
end
|
|
|
|
|
2008-03-26 08:27:52 -04:00
|
|
|
# Compresses a string using gzip.
|
2008-01-03 16:05:12 -05:00
|
|
|
def self.compress(source)
|
|
|
|
output = Stream.new
|
|
|
|
gz = Zlib::GzipWriter.new(output)
|
|
|
|
gz.write(source)
|
|
|
|
gz.close
|
|
|
|
output.string
|
|
|
|
end
|
|
|
|
end
|
2011-02-09 16:47:32 -05:00
|
|
|
end
|