Skip to content

Instantly share code, notes, and snippets.

@adriaant
Created September 23, 2010 02:05
Show Gist options
  • Save adriaant/592940 to your computer and use it in GitHub Desktop.
Save adriaant/592940 to your computer and use it in GitHub Desktop.
['rubygems', 'pathname', 'zip/zip', 'fileutils'].each {|x| require x}
UUIDchars = ("a".."f").to_a + ("0".."9").to_a
def uuid_seg(len)
ret = ""
1.upto(len) { |i| ret << UUIDchars[rand(UUIDchars.size-1)] }; ret
end
def random_uuid
"#{uuid_seg(8)}"
end
def extract_zip_to_tempdir(zip_path)
temp_root = Pathname.new((ENV['TEMP'] || ENV['TMP'] || '/tmp'))
raise "Can't find a temp directory" unless temp_root.exist?
# Make unique temporary directory
temp_dir = nil
while (temp_dir = temp_root.join(random_uuid())).exist?
nil
end
temp_dir.mkpath
Zip::ZipFile.open(zip_path) do |zf|
zf.each do |e|
#ignore osx specific file info
next if e.name =~ /__MACOSX/ or e.name =~ /\.DS_Store/ or !e.file?
#flatten the directory
zf.extract(e.name, File.join(temp_dir, Pathname.new(e.name).basename))
end
end
temp_dir.to_s
end
puts extract_zip_to_tempdir('sample.zip')
# to get rid of directory after handling the contents:
# FileUtils.rm_rf temp_dir.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment