7
votes

In my Rails app I would like to allow users to upload either image or non-image files via Carrierwave. Currently Carrierwave is working fine handeling and processing image files, but unfortunately its dropping non-images files completely. Is there a clean way for a single Carrierwave uploader to process both image and non-image files?

I'll include my current uploader below:

class AssetUploader < CarrierWave::Uploader::Base

  include CarrierWave::MiniMagick

  storage :file

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

  version :thumb do
   process :resize_to_fill => [300, 300]
  end

  version :icon do
   process :resize_to_fill => [48, 48]
  end

  def extension_white_list
    %w(jpg jpeg gif png pdf doc xls docx xlsx ppt)
  end

end
2
I haven't used CarrierWave gem, but with Paperclip this is pretty trivial. Looking over CW's readme, using it looks waaaaaay more complicated than using Paperclip, as well. Just my $.02Yardboy
You're right. I actually ended up switching back to Paperclip, heh.jklina

2 Answers

2
votes

I had this exact problem. I solved it with the hoary comp sci solution of one-more-level-of-indirection: a trampoline/thunk method that dynamically decides whether to process based on file extension.

You can find the implementation here: https://gist.github.com/995663

(the naive approach of introducing logic in the version block actually doesn't work because of how the CarrierWave DSL works - the logic needs to be deferred until invocation)

I hope that helps.

1
votes

I know this has been answered, but aaron's answer doesn't completely solve the problem. You can use what he suggested at https://gist.github.com/995663 if you only need to call process, but not if you want to selectively process with version.

For version, see the carrierwave wiki page here: https://github.com/jnicklas/carrierwave/wiki/How-to%3A-Do-conditional-processing

You can now do this in your code, and it will only process the version block on images

version :thumb, :if => :image? do
  process ...
end

protected

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