在 Rails 中压缩目录 [英] Zipping a directory in Rails

查看:24
本文介绍了在 Rails 中压缩目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在 ruby​​ on rails 中压缩目录?我试过 ruby​​zip 没有成功.我不需要单独压缩目录的内容,只需压缩目录本身.

解决方案

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

def 压缩(路径)宝石'rubyzip'需要'zip/zip'需要'zip/zipfilesystem'path.sub!(%r[/$],'')archive = File.join(path,File.basename(path))+'.zip'FileUtils.rm 存档,:force=>trueZip::ZipFile.open(archive, 'w') 做 |zipfile|目录["#{path}/**/**"].reject{|f|f==archive}.each do |file|zipfile.add(file.sub(path+'/',''),file)结尾结尾结尾

<块引用>

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

使用命令的另一种方法

Dir["*"].each do |file|如果 File.directory?(file)#TODO 添加操作系统特定,# 7z 或 tar .`zip -r "#{file}.zip" "#{file}"`结尾结尾

<块引用>

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

更新

感谢 Mahmoud Khaled 的编辑/更新

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

How do i go about zipping a directory in ruby on rails? I've tried rubyzip without success. I don't need to zip the contents of the dir individually just zip the dir itself.

解决方案

You are going to have to loop through the items in the directory to add an entry in the compressed file.

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/

Another way to do it with a command

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

Update

Thank you Mahmoud Khaled for the edit/update

for the new version use Zip::File.open instead of Zip::ZipFile.open

这篇关于在 Rails 中压缩目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆