Skip to content

Instantly share code, notes, and snippets.

@jpemberthy
Created January 25, 2011 21:08
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpemberthy/795665 to your computer and use it in GitHub Desktop.
Save jpemberthy/795665 to your computer and use it in GitHub Desktop.
class Message < ActiveRecord::Base
validate :image_size_validation, :if => Proc.new { |m| m.image.present? }
mount_uploader :image, MessageImageUploader
private
def image_size_validation
errors[:image] << "should be less than 2MB" if image.size > 2.megabytes
end
end
Copy link

ghost commented Apr 18, 2011

Replace this:

validate :image_size_validation, :if => Proc.new { |m| m.image.present? }

with that:

validate :image_size_validation, :if => "image?"

for cleaner code.

@jpemberthy
Copy link
Author

Ah that's sugar, thanks!

@chrisbloom7
Copy link

I took your basic idea and turned it into a Rails 3 style validator. It's basically a clone of the built-in validates_length_of validator, but checks the file size instead. https://gist.github.com/1009861

@jpemberthy
Copy link
Author

Cool, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment