Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Unzip String

Tags:

ruby

zip

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?

like image 544
pex Avatar asked May 03 '11 14:05

pex


3 Answers

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
like image 53
Lluís Avatar answered Oct 15 '22 00:10

Lluís


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
like image 2
maerics Avatar answered Oct 15 '22 00:10

maerics


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
like image 1
Roman Avatar answered Oct 14 '22 23:10

Roman