Class: ActiveStorageValidations::SizeValidator

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

Overview

:nodoc:

Constant Summary collapse

AVAILABLE_CHECKS =
%i[less_than less_than_or_equal_to greater_than greater_than_or_equal_to between].freeze

Instance Method Summary collapse

Instance Method Details

#check_validity!Object

Raises:

  • (ArgumentError)


9
10
11
12
13
# File 'lib/active_storage_validations/size_validator.rb', line 9

def check_validity!
  return true if AVAILABLE_CHECKS.any? { |argument| options.key?(argument) }

  raise ArgumentError, 'You must pass either :less_than, :greater_than, or :between to the validator'
end

#content_size_valid?(file_size) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/active_storage_validations/size_validator.rb', line 36

def content_size_valid?(file_size)
  if options[:between].present?
    options[:between].include?(file_size)
  elsif options[:less_than].present?
    file_size < options[:less_than]
  elsif options[:less_than_or_equal_to].present?
    file_size <= options[:less_than_or_equal_to]
  elsif options[:greater_than].present?
    file_size > options[:greater_than]
  elsif options[:greater_than_or_equal_to].present?
    file_size >= options[:greater_than_or_equal_to]
  end
end

#max_sizeObject



54
55
56
# File 'lib/active_storage_validations/size_validator.rb', line 54

def max_size
  options[:between]&.max || options[:less_than] || options[:less_than_or_equal_to]
end

#min_sizeObject



50
51
52
# File 'lib/active_storage_validations/size_validator.rb', line 50

def min_size
  options[:between]&.min || options[:greater_than] || options[:greater_than_or_equal_to]
end

#validate_each(record, attribute, _value) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/active_storage_validations/size_validator.rb', line 15

def validate_each(record, attribute, _value)
  # only attached
  return true unless record.send(attribute).attached?

  files = Array.wrap(record.send(attribute))

  errors_options = {}
  errors_options[:message] = options[:message] if options[:message].present?

  files.each do |file|
    next if content_size_valid?(file.blob.byte_size)

    errors_options[:file_size] = number_to_human_size(file.blob.byte_size)
    errors_options[:min_size] = number_to_human_size(min_size)
    errors_options[:max_size] = number_to_human_size(max_size)

    record.errors.add(attribute, :file_size_out_of_range, **errors_options)
    break
  end
end