Search code examples
ruby-on-railsfile-uploadcarrierwavermagick

Altering CarrierWave error message when catching error from rmagick


I am using CarrierWave + rmagick gems to upload image to server. When I am uploading a normal file, everything goes fine. But when I upload malformed file, the form error doesn't display CarrierWave error, it displays the error which appears when running rmagick.

A simple example. I have User model, and an uploader inside it like that:

class User < ActiveRecord::Base
  ...
  mount_uploader :avatar, PictureUploader
end

(the avatar is a stringfield)

Now, the uploader is defined here:

class BaseImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick
  storage :fog

  def extension_white_list
    %w(jpg jpeg gif png)
  end
end


class PictureUploader < BaseImageUploader
  def default_url
    'placeholder.png'
  end

  def store_dir
    'images/pictures'
  end

  version :thumb do
    process resize_to_fit: [50, 50]
  end

  version :medium do
    process resize_to_fill: [400, 400]
  end

  version :small_square do
    process resize_to_fill: [200, 200]
  end
end

Then I create an empty file, for example, with touch ~/Desktop/file.jpg, and trying to upload it via the form, and here I am getting a validation error:

Avatar Failed to manipulate with rmagick, maybe it is not an image? Original Error: Empty input file `<foldername>/public/uploads/tmp/1470905765-10111-5893/thumb_file.jpg' @ error/jpeg.c/JPEGErrorHandler/322

I tried using ming_magick instead of rmagick, but the result is the same (with slightly different error message)

Can I do something to alter this validation message to say something like Avatar Your image is invalid instead of the default?


Solution

  • Hm, actually that was pretty easy: I just needed to add a string to i18n, like that:

    errors.messaging.rmagick_processing_error: "Error processing image"