我如何在 ruby on Rails 中压缩目录?我尝试过 rubyzip 但没有成功。我不需要单独压缩目录的内容,只需压缩目录本身。
您将必须循环遍历目录中的项目才能在压缩文件中添加条目。
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
http://grosser.it/2009/02/04/compressing-a-folder-to-a-zip-archive-with-ruby/ 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
http://ruby-indah-elegan.blogspot.com/2008/12/zipping-folders-in-folder-ruby-script.html http://ruby-indah-elegan.blogspot.com/2008/12/zipping-folders-in-folder-ruby-script.html
Update
感谢 Mahmoud Khaled 的编辑/更新
供新版本使用Zip::File.open
代替Zip::ZipFile.open
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)