Class: DimensionsValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/aspecta.rb

Constant Summary collapse

DIMENSIONS =
[:width, :height]
ATTRIBUTES =
{ :minimum => :>=, :maximum => :<= }
MESSAGES =
{
  :width => {
    :minimum => :image_is_too_narrow,
    :maximum => :image_is_too_wide
  },
  :height => {
    :minimum => :image_is_too_short,
    :maximum => :image_is_too_tall
  }
}

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/aspecta.rb', line 18

def validate_each(record, attribute, value)
  return if value.file.nil?

  if options.empty?
    raise ArgumentError, "Specify the :width and / or :height option"
  end

  DIMENSIONS.each do |dimension|
    unless options[dimension].nil?
      if (ATTRIBUTES.keys & options[dimension].keys).empty?
        raise ArgumentError,
          "Specify the :minimum and / or :maximum option for :#{dimension}"
      end
    end
  end

  dimensions = FastImage.size value.path

  DIMENSIONS.each_with_index do |dimension, index|
    next if options[dimension].nil?

    options[dimension].each do |measure, size|
      unless dimensions[index].send(ATTRIBUTES[measure], size)
           record.errors.add(attribute,
            MESSAGES[dimension][measure],
            :size => size
          )
      end
    end
  end
end