Reputation: 5112
i have a functionality where all the uploaded files are first saved to a public/submitted_folder.Now the enhancement to it this functionality is that the user can view all the uploaded files in zip.i have implemented the functionality that allows user to download the files in zip format.now i have a problem here.i need to delete the newly generated zip file after its downloaded.I want to scan the submitted_folder to scan if any zip files exists and then delete it.how can i do that.what if there are more subfolders such as submitted_folder/folder1/folder2,how can i scan all of them to find and delete any zip files.i referred api for File in ruby,but confused...
Upvotes: 0
Views: 1255
Reputation: 8331
When working with files, try sticking with the Dir
and File
methods. There are great tutorials out there to get you started, I'd suggest this screencast.
When you are in the right directory, grabbing and deleting zip files is easy.
Grab all zip-files
files = Dir.glob("*.zip")
Deleting a certain file:
File.delete("#{file}")
Extracting the files is a bit more tricky, I myself created a folder to put all the extracted files into and then worked from there. You will also need the rubyzip
gem to handle the ZIP files better.
require 'zip/zip'
# creates a directory with a name
Dir.mkdir("#{Dir.pwd}/#{name}") unless File.exists?("#{Dir.pwd}/#{name}")
# opens up the zip file
zipfile = Zip::ZipFile::open(Dir.pwd + "/" + zip_path)
# changes the working directory to the newly created folder
Dir.chdir "#{name}"
# unzips the zip and returns the xml files in it
files = []
zipfile.each do |file|
zipfile.extract(file, "#{Dir.pwd}/#{file.name}") unless File.exists?("#{Dir.pwd}/#{file.name}")
end
As it turns out, there's a simple function to get search the current directory and all the subdirectories. **
being the key
all_zip_files = Dir.glob("**/*.zip")
After you grabbed those files, you can extract, delete or do whatever you wish :)
Upvotes: 0
Reputation: 29369
Assuming that you are using linux, you can execute bash commands from ruby.
Below is the linux command that removes all the files with extension .zip under the path "path"(including sub directories)
find path -type f -name *.zip -delete
execute it from app using
system("find path -type f -name *.zip -delete")
or
`find path -type f -name *.zip -delete`
Upvotes: 1