2012-07-18 56 views
-1

我想用RubyZip压缩目录中包含的所有文件。下面是我有:用Ruby on Rails压缩目录中的文件

def bundle 
     #create the ZIPfile with the title of (:id).zip 
bundle_filename = "public/attachments/#{self.id}/#{self.id}.zip" 

     #open the ZIPfile in order to add items in 
Zip::ZipFile.open(bundle_filename, Zip::ZipFile::CREATE) { 
    |zipfile| 
    Dir.foreach("public/attachments/#{self.id}") do |item| 
    t = File.open(item) 
    zipfile.add(t, "public/attachments/#{self.id}") 
    end 
    } 

    #change permissions on ZIPfile 
    File.chmod(0644, bundle_filename) 
    self.save 
    end 

这成功地执行了第一行,并创建具有正确名称的ZIP文件,但它不加入包含在该目录中的所有文件。有任何想法吗?

+0

你确定'Dir.foreach'调用是添加项目吗?你可以使用'Rails.logger'来调试。 – tadman 2012-07-18 18:21:23

+0

看看这个,http://stackoverflow.com/questions/11525484/zipping-all-files-in-a-dir – PriteshJ 2012-07-18 18:23:36

+0

Wohooo,是来自同一用户的同一个问题;) – PriteshJ 2012-07-18 18:26:07

回答

0

我不知道这是否是最正确的方法,但这对我有用。 这种拉链拉链

require 'zip/zip' 

    def bundle 
     bundle_filename = "abc.zip" 
     FileUtils.rm "abc.zip",:force => true 
     dir = "testruby" 
     Zip::ZipFile.open(bundle_filename, Zip::ZipFile::CREATE) { |zipfile| 
     Dir.foreach(dir) do |item| 
      item_path = "#{dir}/#{item}" 
      zipfile.add(item,item_path) if File.file?item_path 
     end 
     } 
    File.chmod(0644,bundle_filename) 
    end 
2

所有从目录中的文件和文件夹,使您的生活更轻松,并使用命令行功能在Ruby方法:

在此实现,我拉上一个轨道目录,所以在Rails函数的帮助下,我可以访问该目录的完整路径。你可以自己指定整个路径。

path = Rails.root.to_s + "/public/tmpFiles" 
archive = path + "/tempFilesArchive.zip" 
puts "Path: #{path}" 
puts "Archive: #{archive}" 
`rm "#{archive}"` # remove the archive file, if it exists. 
`zip -rj "#{archive}" "#{path}"` # zip the contents of the directory 

这应该在您压缩的同一个目录中创建一个名为“tempFilesArchive.zip”的zip文件。