我设法将上传的文件压缩如下
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