Last active
February 17, 2016 09:23
-
-
Save dimasjt/ae5612b8e1ae7c31c980 to your computer and use it in GitHub Desktop.
validation for image dimesion with MiniMagick and CarrierWave
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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