Skip to content

Instantly share code, notes, and snippets.

@dimasjt
Last active February 17, 2016 09:23
Show Gist options
  • Save dimasjt/ae5612b8e1ae7c31c980 to your computer and use it in GitHub Desktop.
Save dimasjt/ae5612b8e1ae7c31c980 to your computer and use it in GitHub Desktop.
validation for image dimesion with MiniMagick and CarrierWave
require 'mini_magick'
class ImageabilityValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
if image_changed?(record, attribute, value)
pic = MiniMagick::Image.open(value.path)
if pic[:height] < options[:min][1] || pic[:width] < options[:min][0]
record.errors.add(attribute, "should be greater than #{options[:min][0]}x#{options[:min][1]} pixels")
end
if options[:wide]
if pic[:height] > pic[:width]
record.errors.add(attribute, "should be wider")
end
end
if value.size > options[:size]
record.errors.add(attribute, "should be less than #{size options[:size]}MB")
end
end
end
protected
def image_changed?(record, attribute, value)
(!value.file.nil? && record.changed? && record.changed.include?(attribute)) || record.try("#{attribute.to_s}_cache")
end
def size(bytes)
bytes / 1.megabyte
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment