-1

RubyZip を使用して、ディレクトリに含まれるすべてのファイルを圧縮しようとしています。ここに私が持っているものがあります:

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 ファイルが作成されますが、そのディレクトリに含まれるすべてのファイルが追加されるわけではありません。何か案は?

4

2 に答える 2

4

ruby メソッドでコマンドライン関数を使用して、作業を楽にしましょう。

この実装では、Rails ディレクトリを圧縮しているので、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 ファイルが作成されます。

于 2015-07-03T06:33:01.377 に答える
1

これが最も正しい方法かどうかはわかりませんが、これは私にとってはうまくいきます。これにより、すべてのファイルとフォルダーが dir から zip に圧縮されます

  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
于 2012-07-18T19:23:47.300 に答える