2008-01-03 16:05:12 -05:00
|
|
|
require 'zlib'
|
|
|
|
require 'stringio'
|
|
|
|
|
|
|
|
module ActiveSupport
|
2012-06-05 00:43:43 -04:00
|
|
|
# A convenient wrapper for the zlib standard library that allows
|
|
|
|
# compression/decompression of strings with gzip.
|
|
|
|
#
|
|
|
|
# gzip = ActiveSupport::Gzip.compress('compress me!')
|
|
|
|
# # => "\x1F\x8B\b\x00o\x8D\xCDO\x00\x03K\xCE\xCF-(J-.V\xC8MU\x04\x00R>n\x83\f\x00\x00\x00"
|
|
|
|
#
|
|
|
|
# ActiveSupport::Gzip.decompress(gzip)
|
|
|
|
# # => "compress me!"
|
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
|
2011-12-24 07:57:54 -05:00
|
|
|
set_encoding "BINARY"
|
2011-02-09 16:47:32 -05:00
|
|
|
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.
|
2012-09-22 05:07:50 -04:00
|
|
|
def self.compress(source, level=Zlib::DEFAULT_COMPRESSION, strategy=Zlib::DEFAULT_STRATEGY)
|
2008-01-03 16:05:12 -05:00
|
|
|
output = Stream.new
|
2012-09-22 05:07:50 -04:00
|
|
|
gz = Zlib::GzipWriter.new(output, level, strategy)
|
2008-01-03 16:05:12 -05:00
|
|
|
gz.write(source)
|
|
|
|
gz.close
|
|
|
|
output.string
|
|
|
|
end
|
|
|
|
end
|
2011-02-09 16:47:32 -05:00
|
|
|
end
|