Class: UploaderImageDimensionsValidator

Inherits:
ActiveModel::Validations::FileContentTypeValidator
  • Object
show all
Defined in:
app/validators/uploader_image_dimensions_validator.rb

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



48
# File 'app/validators/uploader_image_dimensions_validator.rb', line 48

def check_validity!; end

#extract_image(file) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'app/validators/uploader_image_dimensions_validator.rb', line 34

def extract_image(file)
  return unless file.try(:content_type).to_s.start_with?("image")

  if file.is_a?(ActionDispatch::Http::UploadedFile)
    MiniMagick::Image.new(file.path)
  elsif file.is_a?(ActiveStorage::Attached) && file.blob.persisted?
    MiniMagick::Image.read(file.blob.download)
  end
rescue ActiveStorage::FileNotFoundError
  # Although the blob is persisted, the file is not available to download and analyze
  # after committing the record
  nil
end

#validate_each(record, attribute, value) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'app/validators/uploader_image_dimensions_validator.rb', line 9

def validate_each(record, attribute, value)
  begin
    values = parse_values(value)
  rescue JSON::ParserError
    record.errors.add attribute, :invalid
    return
  end

  return if values.empty?

  uploader = record.attached_uploader(attribute) || record.send(attribute)
  return unless uploader.is_a?(Decidim::ApplicationUploader)

  values.each do |val|
    validate_image_size(record, attribute, val, uploader)
  end
end

#validate_image_size(record, attribute, file, uploader) ⇒ Object



27
28
29
30
31
32
# File 'app/validators/uploader_image_dimensions_validator.rb', line 27

def validate_image_size(record, attribute, file, uploader)
  return unless uploader.validable_dimensions
  return if (image = extract_image(file)).blank?

  record.errors.add attribute, I18n.t("carrierwave.errors.file_resolution_too_large") if image.dimensions.any? { |dimension| dimension > uploader.max_image_height_or_width }
end