简体   繁体   中英

rails rubyzip make a copy of multiple zip files inside a new zipfile

So basically I am creating a bunch of zip files which contains a pwe and pws files inside it.

The following code generates a bunch of zip files which is named as orgname_org_member_orguser1.zip which contains 2 files(a pws and pwe)

 @successful_orgs.each do |org|
    file = "#{RAILS_ROOT}/my-data/#{org[:location]}_#{org[:member]}_#{org[:username]}.zip"
    generate_file(ups_file, org)
 end

  def generate_file(file, org)
    zipfile = Zip::ZipFile.open(file, Zip::ZipFile::CREATE)
    pwe_text, pws_text = MyGenerator.password
    pwe_file =  "#{RAILS_ROOT}/tmp/#{org[:location]}_#{org[:member]}.pwe"
    pws_file =  "#{RAILS_ROOT}/tmp/#{org[:location]}_#{org[:member]}.pws"

    File.open(pwe_file, 'w') { |file| file.write(pwe_text) }
    File.open(pws_file, 'w') { |file| file.write(pws_text) }

    zipfile.add("#{org[:location]}_#{org[:member]}.pwe", pwe_file)
    zipfile.add("#{org[:location]}_#{org[:member]}.pws", pws_file)
    zipfile.close

    File.delete(pwe_file)
    File.delete(pws_file)    
  end

I want to let the code do what is doing(create the zip files and store it the specified path)

But in addition to the above, I also want to create another zip file called all.zip which would contain all the zip files created above.

Meaning, all.zip => file1.zip, file2.zip etc

I am not sure how to incoporate that logic in my code above. Any help would be appreciated.

EDIT: I do not want to search and add all the files in the directory. I want to add only the zip files created during the above code.

You can collect all the zip file paths in an array and then add them to a new zip file iteratively:

zip_files = []
@successful_orgs.each do |org|
  file = "#{RAILS_ROOT}/my-data/#{org[:location]}_#{org[:member]}_#{org[:username]}.zip"
  zip_files << file
  generate_file(file, org)
end

all_zipped = Zip::ZipFile.open("#{RAILS_ROOT}/tmp/all.zip", Zip::ZipFile::CREATE)
zip_files.each do |f|
  all_zipped.add(zip_file)
end

Note that you're not going to gain any additional compression by doing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM