Skip to navigation

Rollin your own attachment_fu messages evil twin stylee

Published December 03, 2007

On the back of Patrick Crowley’s Roll your own attachment_fu validations I got off my butt and made a whole bunch of validations sexier… the result is this snippet/plugin/snippet, evil twin stylee, to give friendlier attachment validations.

Use it like so:


class Photo < ActiveRecord::Base
  has_attachment :content_type => :image,
                 :max_size => 10.megabytes,

  validates_attachment :content_type => "The file you uploaded was not a JPEG, PNG or GIF",
                       :size         => "The image you uploaded was larger than the maximum size of 10MB" 
end

Just chuck this into vendor/plugins/attachment_fu_validates_attachment/init.rb:

Technoweenie::AttachmentFu::InstanceMethods.module_eval do
  protected
    def attachment_valid?
      if self.filename.nil?
        errors.add_to_base attachment_validation_options[:empty]
        return
      end
      [:content_type, :size].each do |option|
        if attachment_validation_options[option] && attachment_options[option] && !attachment_options[option].include?(self.send(option))
          errors.add_to_base attachment_validation_options[option]
        end
      end
    end
end

Technoweenie::AttachmentFu::ClassMethods.module_eval do
  # Options: 
  # *  <tt>:empty</tt> - Base error message when no file is uploaded. Default is "No file uploaded" 
  # *  <tt>:content_type</tt> - Base error message when the uploaded file is not a valid content type.
  # *  <tt>:size</tt> - Base error message when the uploaded file is not a valid size.
  #
  # Example:
  #   validates_attachment :content_type => "The file you uploaded was not a JPEG, PNG or GIF",
  #                        :size         => "The image you uploaded was larger than the maximum size of 10MB" 
  def validates_attachment(options={})
    options[:empty] ||= "No file uploaded" 
    class_inheritable_accessor :attachment_validation_options
    self.attachment_validation_options = options
    validate :attachment_valid?
  end
end

and say goodbye to errors messages like:

  • Content type can’t be blank
  • Content type is not included in the list
  • Size can’t be blank
  • Size is not included in the list
  • Filename can’t be blank

and say hello to:

  • No file uploaded

and:

  • The file you uploaded was not a JPEG, PNG or GIF
  • The image you uploaded was larger than the maximum size of 10MB

Archived comments

Comments were previously allowed on articles. Though no new comments are being accepted you can see the old comments below.

  1. Dylan

    Thanks, Tim. I worked this into an app I am building this afternoon.

    Also, if you haven’t heard; it looks like a_fu is getting a little update love these days.

    http://railsontherun.com/2007/11/28/attachment_fu-updated

  2. Tim Lucas

    Yep don’t worry, I’m on it :)

  3. Patrick Crowley

    Yeah, Matt’s been going crazy on a_fu lately.

    Nice work, Tim!

  4. Fulvio

    Howdy,

    Thanks for this! I’m using this on my new site at the moment. I’m noticing some random/weird behavior when uploading a photo though.

    It always gives me the following validation message:

    The image you uploaded was larger than the maximum size of 3 megabytes.

    I’m using the following code in my photo.rb model. The weird thing is is that when I try the same image and title over and over again it eventually uploads it…

    [code]
      validates_attachment  :content_type => "The file you uploaded was not a JPEG, PNG or GIF",
                            :size         => "The image you uploaded was larger than the maximum size of 3 megabytes" 
    [/code]
  5. Simon Tokumine

    For those of you wondering why you always get the content_type and size errors even when no file has been uploaded, replace self.filename.nil? with self.filename.blank? in the following section of code:

    if self.filename.nil? errors.add_to_base attachment_validation_options[:empty] return end
  6. Tomash

    Hi! Great idea, thanks. We’re using it with success together with Gloc for some localized messages.

    One error, though: the :empty option gets saved differently than the remaining ones, with empty message being the key in error array (and not the value, as it should be / as the rest are). When someone is rolling their own error_messages_for to get rid of english model names, this one can be a bit of an issue. Quick fix: replace
    if self.filename.nil?
      errors.add attachment_validation_options[:empty]
      eturn
    end
    if self.filename.nil?
      errors.add :empty, attachment_validation_options[:empty]
      eturn
    end
  7. Tomash

    replace “block” WITH “block” of course. And I ate “r” in return accidentally.

  8. Steven Holloway

    I found during a rails 2.1 and rspec 1.1.4 upgrade of a large well spec’d app that validations using the above method were failing. The error messages were being added by error.add_to_base
    
    errors => {"base" => "error message"}
    
    our spec is looking for
    
    errors => {"size" => "error message"}
    
    Thus the fix was similar to what Tomash has done with :empty.
    
    errors.add option, attachment_validation_options[option]
    

Articles

toolmantim

I'm Tim Lucas, a user experience designer and developer currently in Sydney Australia.

I run a web application design and development company Agency Rainford, present on various technical topics, snap the occasional photo, tweet my going-ons, share teh codes and post other tid-bits to the tumble.

Most recently I published LAN hacking with Bananajour (June 11, 2009)

Shoot an email to and say hello.

Powered by faux western Buddhism