使用不同文件类型上载Carrierwave文件

Muh*_*mbi 9 ruby pdf ruby-on-rails image carrierwave

我有以下作为我的FileUploader:

class FileUploader < CarrierWave::Uploader::Base
  include CarrierWave::MiniMagick

  version :thumb, if: :image? do
    # For images, do stuff here
  end

  version :preview, if: :pdf? do
     # For pdf, do stuff here
  end

  protected

  def image?(new_file)
    new_file.content_type.start_with? 'image'
  end

  def pdf?(new_file)
    new_file.content_type.start_with? 'application'
  end

end
Run Code Online (Sandbox Code Playgroud)

我从carrierwave github页面得到了这个.它主要起作用,但如果我不想要不同的版本呢?我基本上只是想做某些过程,如果它是一个pdf,或某些过程,如果它是一个图像.我可能会在将来允许其他类型的文件,所以如果我有一个简单的方法也可以这样做很酷.

举个例子,我可能想要使用imgoptim(如果它是图像),然后使用pdf优化库(如果它是pdf等).

我试过了:

if file.content_type = "application/pdf"
    # Do pdf things
elsif file.content_type.start_with? 'image'
    # Do image things
end
Run Code Online (Sandbox Code Playgroud)

但得到错误:NameError: (undefined local variable or method文件'for FileUploader:Class`

Oja*_*ash 9

你应该尝试这样使用

class FileUploader < CarrierWave::Uploader::Base  
  include CarrierWave::MiniMagick

  process :process_image, if: :image?
  process :process_pdf, if: :pdf?

  protected

  def image?(new_file)
    new_file.content_type.start_with? 'image'
  end

  def pdf?(new_file)
    new_file.content_type.start_with? 'application'
  end

  def process_image
    # I process image here
  end

  def process_pdf
    # I process pdf here
  end
end
Run Code Online (Sandbox Code Playgroud)