Reputation: 126
There is a zipfile. It can either have 10 files or one folder. This folder will have the 10 files. Now, if the zipfile has a folder, then i have to move all the files one directory above i.e.
zipfile.zip has folder. folder has 10 files. normally, if i unzip, i get zipfile/folder/10files. Now, I have to get like zipfile/10files. ie. move all the files one directory above.
How to do this? Please help.
Upvotes: 1
Views: 1268
Reputation: 7561
If you don't mind using Linux unzip
and really aren't worried about subdirectories:
def unzip(file)
to = File.join(File.dirname(file), File.basename(file, ".*"))
Dir.mkdir(to) unless File.exists?(to)
`unzip -j #{file} -d #{to}`
end
# unzip('yourfile.zip')
This method creates a new directory in the same directory as the zip file with the same name as the zipfile (minus extension). It then extracts (using unzip
) the zip file into that directory, ignoring all paths (the -j
flag tells unzip
to junk paths).
EDIT
Per your comment, here is a way to do it without system calls:
def unzip(file)
Zip::ZipFile.open(file) do |zipfile|
to = File.join(File.dirname(file), File.basename(file, ".*"))
FileUtils.mkdir(to) unless File.exists? to
zipfile.each do |f|
if f.file? # Don't extract directories
fpath = File.join(to, File.basename(f.name))
zipfile.extract(f, fpath) unless File.exists?(fpath)
end
end
end
end
Upvotes: 1