Class: ActiveStorageValidations::SizeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Includes:
Errorable, OptionProcUnfolding, Symbolizable
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
ERROR_TYPES =
%i[
  file_size_not_less_than
  file_size_not_less_than_or_equal_to
  file_size_not_greater_than
  file_size_not_greater_than_or_equal_to
  file_size_not_between
].freeze

Instance Method Summary collapse

Methods included from Errorable

#add_error, #initialize_error_options

Methods included from OptionProcUnfolding

#unfold_procs

Instance Method Details

#check_validity!Object



29
30
31
32
33
# File 'lib/active_storage_validations/size_validator.rb', line 29

def check_validity!
  unless AVAILABLE_CHECKS.one? { |argument| options.key?(argument) }
    raise ArgumentError, 'You must pass either :less_than(_or_equal_to), :greater_than(_or_equal_to), or :between to the validator'
  end
end

#validate_each(record, attribute, _value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/active_storage_validations/size_validator.rb', line 35

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

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

  files.each do |file|
    next if is_valid?(file.blob.byte_size, flat_options)

    errors_options = initialize_error_options(options, file)
    errors_options[:file_size] = number_to_human_size(file.blob.byte_size)
    errors_options[:min_size] = number_to_human_size(min_size(flat_options))
    errors_options[:max_size] = number_to_human_size(max_size(flat_options))
    keys = AVAILABLE_CHECKS & flat_options.keys
    error_type = "file_size_not_#{keys.first}".to_sym

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