Class: ActiveStorageValidations::TotalSizeValidator

Inherits:
BaseSizeValidator
  • Object
show all
Defined in:
lib/active_storage_validations/total_size_validator.rb

Constant Summary collapse

ERROR_TYPES =
%i[
  total_file_size_not_less_than
  total_file_size_not_less_than_or_equal_to
  total_file_size_not_greater_than
  total_file_size_not_greater_than_or_equal_to
  total_file_size_not_between
].freeze

Constants inherited from BaseSizeValidator

BaseSizeValidator::AVAILABLE_CHECKS

Instance Method Summary collapse

Methods inherited from BaseSizeValidator

#check_validity!, #initialize

Methods included from Errorable

#add_error, #initialize_error_options

Methods included from OptionProcUnfolding

#unfold_procs

Constructor Details

This class inherits a constructor from ActiveStorageValidations::BaseSizeValidator

Instance Method Details

#validate_each(record, attribute, _value) ⇒ Object



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

def validate_each(record, attribute, _value)
  custom_check_validity!(record, attribute)

  return true unless record.send(attribute).attached?

  files = Array.wrap(record.send(attribute))
  flat_options = unfold_procs(record, self.options, AVAILABLE_CHECKS)

  total_file_size = files.sum { |file| file.blob.byte_size }

  return true if is_valid?(total_file_size, flat_options)

  errors_options = initialize_error_options(options, nil)
  populate_error_options(errors_options, flat_options)
  errors_options[:total_file_size] = number_to_human_size(total_file_size)

  keys = AVAILABLE_CHECKS & flat_options.keys
  error_type = "total_file_size_not_#{keys.first}".to_sym

  add_error(record, attribute, error_type, **errors_options)
end