pex
pex

Reputation: 7761

Ruby Unzip String

I have to work with a zipped (regular Zip) string in Ruby. Apparently I can't save a temporary file with Ruby-Zip or Zip-Ruby.

Is there any practicable way to unzip this string?

Upvotes: 6

Views: 5246

Answers (5)

Lluís
Lluís

Reputation: 1317

rubyzip supports StringIO since version 1.1.0

require "zip"
# zip is the string with the zipped contents
Zip::InputStream.open(StringIO.new(zip)) do |io|
  while (entry = io.get_next_entry)
    puts "#{entry.name}: '#{io.read}'"
  end
end

Upvotes: 8

fearless_fool
fearless_fool

Reputation: 35239

As @Roman mentions, rubyzip currently lacks reading and writing of IO objects (including StringIO.new(s)). Try using zipruby instead, like this:

gem install zipruby

require 'zipruby'

# Given a string in zip format, return a hash where 
# each key is an zip archive entry name and each
# value is the un-zipped contents of the entry
def unzip(zipfile)
  {}.tap do |h|
    Zip::Archive.open_buffer(zipfile) do |archive|
      archive.each {|entry| h[entry.name] = entry.read }
    end
  end
end

Upvotes: 0

maerics
maerics

Reputation: 156682

See Zip/Ruby Zip::Archive.open_buffer(...):

require 'zipruby'
Zip::Archive.open_buffer(str) do |archive|
  archive.each do |entry|
    entry.name
    entry.read
  end
end

Upvotes: 2

Roman
Roman

Reputation: 13058

As the Ruby-Zip seems to lack support of reading/writing to IO objects, you can fake File. What you can do is the following:

  1. Create a class called File under Zip module which inherits from StringIO, e.g. class Zip::File < StringIO
  2. Create the exists? class method (returns true)
  3. Create the open class method (yields the StringIO to the block)
  4. Stub close instance method (if needed)
  5. Perhaps it'll need more fake methods

Upvotes: 1

Elad
Elad

Reputation: 3130

The zlib library. Works fine with StringIO.

Upvotes: -1

Related Questions