Class: DimensionsValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- DimensionsValidator
- Defined in:
- lib/image_validators/dimensions_validator.rb
Constant Summary collapse
- AVAILABLE_CHECKS =
[:less_than, :less_than_or_equal_to, :greater_than, :greater_than_or_equal_to, :equal_to]
Instance Method Summary collapse
- #check_validity! ⇒ Object
- #meet_constraints(operation, image_dimension, threshold) ⇒ Object
- #validate_each(record, attribute, value) ⇒ Object
Instance Method Details
#check_validity! ⇒ Object
53 54 55 56 57 |
# File 'lib/image_validators/dimensions_validator.rb', line 53 def check_validity! unless (AVAILABLE_CHECKS).any? { |argument| .has_key?(argument) } raise ArgumentError, "You must pass either :less_than, :less_than_or_equal_to, :greater_than, :greater_than_or_equal_to, or :equal_to to the validator" end end |
#meet_constraints(operation, image_dimension, threshold) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/image_validators/dimensions_validator.rb', line 6 def meet_constraints(operation, image_dimension, threshold) return true unless threshold case operation when :less_than return image_dimension < threshold when :less_than_or_equal_to return image_dimension <= threshold when :greater_than return image_dimension > threshold when :greater_than_or_equal_to return image_dimension >= threshold when :equal_to return image_dimension == threshold else raise ArgumentError, "You must pass either :less_than, :less_than_or_equal_to, :greater_than, :greater_than_or_equal_to, or :equal_to to the validator" end end |
#validate_each(record, attribute, value) ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/image_validators/dimensions_validator.rb', line 25 def validate_each(record, attribute, value) if record.send("#{attribute}?".to_sym) and value.queued_for_write[:original] dimensions = Paperclip::Geometry.from_file(value.queued_for_write[:original].path) .slice(*AVAILABLE_CHECKS).each do |operation, params| width = params[:width] height = params[:height] # Width if (not meet_constraints(operation, dimensions.width.to_i, width)) record.errors[attribute] << ([:message] || I18n.t('image_validators.errors.' + operation.to_s + '.width', default: "width must be " + operation.to_s.humanize.downcase + " %{width}px", width: width)) end # Height if (not meet_constraints(operation, dimensions.height.to_i, height)) record.errors[attribute] << ([:message] || I18n.t('image_validators.errors.' + operation.to_s + '.height', default: "height must be " + operation.to_s.humanize.downcase + " %{height}px", height: width)) end end end end |