在Rails中压缩目录

Del*_*llo 6 ruby zip ruby-on-rails rubyzip

我如何在rails上的ruby中压缩目录?我试过rubyzip没有成功.我不需要单独压缩dir的内容只是压缩dir本身.

Hit*_*eeb 12

您将不得不遍历目录中的项目以在压缩文件中添加条目.

def compress(path)
  gem 'rubyzip'
  require 'zip/zip'
  require 'zip/zipfilesystem'

  path.sub!(%r[/$],'')
  archive = File.join(path,File.basename(path))+'.zip'
  FileUtils.rm archive, :force=>true

  Zip::ZipFile.open(archive, 'w') do |zipfile|
    Dir["#{path}/**/**"].reject{|f|f==archive}.each do |file|
      zipfile.add(file.sub(path+'/',''),file)
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

http://grosser.it/2009/02/04/compressing-a-folder-to-a-zip-archive-with-ruby/

使用命令执行此操作的另一种方法

Dir["*"].each do |file|
  if File.directory?(file)
    #TODO add OS specific,
    #  7z or tar .
    `zip -r "#{file}.zip" "#{file}"`
  end
end
Run Code Online (Sandbox Code Playgroud)

http://ruby-indah-elegan.blogspot.com/2008/12/zipping-folders-in-folder-ruby-script.html

更新

感谢Mahmoud Khaled的编辑/更新

对于新版本使用Zip::File.open而不是Zip::ZipFile.open