Skip to content

Instantly share code, notes, and snippets.

@raecoo
Last active August 29, 2015 14:09
Show Gist options
  • Save raecoo/3934f0b12318e3050bc1 to your computer and use it in GitHub Desktop.
Save raecoo/3934f0b12318e3050bc1 to your computer and use it in GitHub Desktop.
image size validator
# Refs: http://stackoverflow.com/questions/7527887/validate-image-size-in-carrierwave-uploader
class ImageSizeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value.blank?
image = MiniMagick::Image.open(value.path)
checks = [
{ :option => :width,
:field => :width,
:function => :'==',
:message =>"width must be %d px."},
{ :option => :height,
:field => :height,
:function => :'==',
:message =>"height must be %d px."},
{ :option => :max_width,
:field => :width,
:function => :'<=',
:message =>"width must be at most %d px."},
{ :option => :max_height,
:field => :height,
:function => :'<=',
:message =>"height must be at most %d px."},
{ :option => :min_width,
:field => :width,
:function => :'>=',
:message =>"width must be at least %d px."},
{ :option => :min_height,
:field => :height,
:function => :'>=',
:message =>"height must be at least %d px."},
]
checks.each do |p|
if options.has_key?(p[:option]) and
!image[p[:field]].send(p[:function], options[p[:option]])
record.errors[attribute] << p[:message] % options[p[:option]]
end
end
end
end
end
# between 300px and 800px in width, and 100px and 500px in height.
validates :image, image_size: {min_width: 300, max_width: 800, min_height: 100, max_height: 500}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment