Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decompress Gzip string in ruby?

Tags:

ruby

gzip

zlib

The above method didn't work for me.
I kept getting incorrect header check (Zlib::DataError) error. Apparently it assumes you have a header by default, which may not always be the case.

The work around that I implemented was:

require 'zlib'
require 'stringio'
gz = Zlib::GzipReader.new(StringIO.new(resp.body.to_s))    
uncompressed_string = gz.read

Zlib by default asumes that your compressed data contains a header. If your data does NOT contain a header it will fail by raising a Zlib::DataError.

You can tell Zlib to assume the data has no header via the following workaround:

def inflate(string)
  zstream = Zlib::Inflate.new(-Zlib::MAX_WBITS)
  buf = zstream.inflate(string)
  zstream.finish
  zstream.close
  buf
end

You need Zlib::Inflate for decompression of a string and Zlib::Deflate for compression

  def inflate(string)
    zstream = Zlib::Inflate.new
    buf = zstream.inflate(string)
    zstream.finish
    zstream.close
    buf
  end

In Rails you can use:

  • ActiveSupport::Gzip.compress("my string")
  • ActiveSupport::Gzip.decompress().

zstream = Zlib::Inflate.new(16+Zlib::MAX_WBITS)