使用carrierwave上传后的Zip文件

时间:2015-04-08 11:43:51

标签: ruby-on-rails-4 carrierwave

我设法将上传的文件压缩如下

class Document < ActiveRecord::Base
  mount_uploader :archive, ArchiveUploader

  before_save :zip_file

  def zip_file
    if has_file? and ! is_file_zipped?
      new_path = File.dirname(archive.current_path)+"/#{archive.filename}"
      system("zip -j -P #{ENV['FILE_PASSWORD']} '#{new_path}' '#{archive.current_path}'")
      self.archive = Rails.root.join(new_path).open
    end
  end
end

class ArchiveUploader < CarrierWave::Uploader::Base
  storage :ftp

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  def filename
    @name ||= "#{timestamp}.zip" if original_filename.present?
  end

  def timestamp
    var = :"@#{mounted_as}_timestamp"
    model.instance_variable_get(var) or model.instance_variable_set(var, Time.now.to_i)
  end
end

这有点太臭了吗?有更优雅的方式吗?

在这里获得灵感https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Use-a-timestamp-in-file-names

0 个答案:

没有答案