Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With Carrierwave and Rails 3 is it possible to nicely manage image and non-image files with the same uploader?

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
like image 224
jklina Avatar asked May 03 '11 20:05

jklina


2 Answers

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.

like image 181
aaron Avatar answered Oct 20 '22 17:10

aaron


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
like image 20
keithepley Avatar answered Oct 20 '22 16:10

keithepley