Class: MiniPaperclip::Validators::GeometryValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/mini_paperclip/validators/geometry_validator.rb

Constant Summary collapse

Error =
Class.new(StandardError)
ALLOW_OPTIONS =
[:less_than_or_equal_to]

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/mini_paperclip/validators/geometry_validator.rb', line 9

def check_validity!
  [:width, :height].each do |key|
    if options[key]
      keys = ALLOW_OPTIONS & options[key].keys
      if keys.empty?
        raise ArgumentError, ":#{key} option should specify the :less_than_or_equal_to ."
      end
    end
  end
end

#validate_each(record, attribute, value) ⇒ Object

validate_attachment :image,

geometry: {
  width: { less_than_or_equal_to: 3000 },
  height: { less_than_or_equal_to: 3000 } }


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/mini_paperclip/validators/geometry_validator.rb', line 24

def validate_each(record, attribute, value)
  return unless value.waiting_write_file
  value.waiting_write_file.rewind
  image_size = ImageSize.new(value.waiting_write_file)
  # invalid format should not relate geometry
  unless image_size.format
    MiniPaperclip.config.logger.info("[mini_paperclip] cannot get image_size from #{value.waiting_write_file.inspect}")
    return
  end

  expected_width_less_than_or_equal_to = options.dig(:width, :less_than_or_equal_to)
  expected_height_less_than_or_equal_to = options.dig(:height, :less_than_or_equal_to)
  unless (!expected_width_less_than_or_equal_to || image_size.width <= expected_width_less_than_or_equal_to) &&
      (!expected_height_less_than_or_equal_to || image_size.height <= expected_height_less_than_or_equal_to)
    record.errors.add(
      attribute,
      :geometry,
      actual_width: image_size.width,
      actual_height: image_size.height,
      expected_width_less_than_or_equal_to: expected_width_less_than_or_equal_to,
      expected_height_less_than_or_equal_to: expected_height_less_than_or_equal_to,
    )
  end
end