ruby-on-rails - 如何在 CarrierWave 进程中创建新文件?

标签 ruby-on-rails process carrierwave

我的用户上传了一个包含 3 个文件(A.ttf、A.svg、A.otf)的 zip 文件,我想在其中存储原始 zip 文件和 3 个字体文件。我用这段代码创建了 3 个版本

version :ttf
    process :font => :ttf
end

version :svg
    process :font => :svg
end

version :otf
    process :font => :otf
end

它成功保存了原始文件的 4 个副本,所有副本都具有正确的文件名。但是,我不知道如何让 CarrierWave 存储单个文件。此代码不起作用。 :(

def font(format)
  new_file = nil

  # Loop through the zip file and extract the files
  Zip::ZipFile.open(@file.file) do |files|
    files.each do |f|
      next unless f.file?

      filename  = f.name.split("/").last
      ext       = filename.split('.').last

      # Save the file with the proper file extension
      new_file = f if ext == format
  end

  # Return the file to be stored by CarrierWave
  new_file
end

最佳答案

好吧,我的头撞在墙上好几个小时后,灯终于亮了。解决方案在于 CarrierWave 如何处理上传。当您定义一个版本时,CW 会使用新名称 ([version name]_original_filename) 复制该文件,并在 current_path 变量中将其提供给您。您可以使用此文件引用做任何您想做的事情(即打开文件并截断​​它,或用随机日期填充它等),完成后 CW 将为您存储该文件。

不知何故,我错过了联系,当我意识到发生了什么事时,我几乎失明了。我在这里回答这个问题是为了帮助其他一些迷失在黑暗中的可怜人。并向世界展示我的无知。 :/

关于ruby-on-rails - 如何在 CarrierWave 进程中创建新文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4968027/

相关文章:

javascript - 渲染js Action 并传递本地

ruby-on-rails - Rspec: ||= 运算符重复计算代码

ruby-on-rails - link_to_if 抛出错误

c++ - 确定进程是否与系统相关

powershell - 检测以相同名称运行的进程数

ruby-on-rails-3.1 - 载波-Rails 3.1-未定义的方法:image_will_change

ruby-on-rails - 在 Rails 中编码视频时出现参数错误

javascript - 如何让 Foundation Reveal Modal 在 Rails 中工作?

python - 当某些项目相互依赖时,如何运行异步进程列表?

ruby-on-rails - Rails3 载波未上传