Skip to content

How to: Do conditional processing

Adam Jahn edited this page Apr 14, 2017 · 12 revisions

If you want to hold both images and regular files as attachments to a model, additional processing (i.e. creating a thumbnail) can be attached only to images.

Here's the example code to create thumbnails when the uploaded file is an image:

version :thumb, :if => :image? do
  process :resize_to_limit => [200, 200]
end

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

If you'll use content_type method make sure to include the MimeTypes module:

class AttachmentUploader < CarrierWave::Uploader::Base
  # include CarrierWave::MimeTypes
  # ^ Include MimeTypes for CarrierWave versions < 1.0.0

  # Call method
  process :set_content_type
end

Just a mention, to avoid multiple checking if it is needless in your case, you could make it like as:

your_model.rb:

attr_accessor :is_thumbnable

your_uploader.rb:

def image?(new_file)
  return model.is_thumbnable unless model.is_thumbnable.nil?
  model.is_thumbnable = \
    begin
      #your condition goes here and it should return true or false, except nil
    end
end
Clone this wiki locally