Class: SizeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/size_validator.rb

Overview

Custom validator for file sizes

Examples:


-> validates :image, size: { less_than: 2.megabytes }
-> validates :image, size: { less_than: 2.megabytes, message: 'is too large, please upload a file smaller than 2MB' }

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



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

def validate_each(record, attribute, value)
  return unless value.present? && value.attached?

  options = instance_values["options"]

  max_size = options.try(:[], :less_than) || 2.megabytes
  message = options.try(:[], :message) || "is too large, please upload a file smaller than #{max_size / 1.megabyte}MB"

  blobs = value.try(:blobs) || value.try(:blob) || raise('unable to find blobs')

  Array(blobs).each do |blob|
    if blob.byte_size > max_size
      record.errors.add(attribute, message)
      break
    end
  end

  true
end