Last active
December 27, 2015 12:49
-
-
Save Sija/7328783 to your computer and use it in GitHub Desktop.
DimensionsValidator to use for images uploaded using Paperclip.
This file contains 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
class DimensionsValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, value) | |
temp_file = value.queued_for_write[:original] | |
return unless temp_file.present? | |
return unless geo = Paperclip::Geometry.from_file(temp_file) | |
options.slice(:width, :height).each_pair do |key, expectation| | |
next unless dimension = geo.send(key) | |
case expectation | |
when Integer | |
record.errors[attribute] << "#{key} must be exactly #{expectation}px" unless dimension == expectation | |
when Range | |
unless dimension.in? expectation | |
record.errors[attribute] << "#{key} must be between #{expectation.min} and #{expectation.max} px" | |
end | |
when String | |
if expectation =~ /^([<>]=?)(\d+)$/ | |
# we directly pass the comparator string as a method call | |
unless dimension.send($1, $2.to_i) | |
human_error = case $1 | |
when '<' then 'smaller than' | |
when '<=' then 'smaller or equal than' | |
when '>' then 'greater than' | |
when '>=' then 'at least' | |
end | |
record.errors[attribute] << "#{key} must be #{human_error} #{$2}px" | |
end | |
else | |
raise ArgumentError, "Incorrect syntax for given #{key} argument" | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment