Class: ActiveStorageValidations::SizeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Includes:
OptionProcUnfolding
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

Methods included from OptionProcUnfolding

#unfold_procs

Instance Method Details

#check_validity!Object

Raises:

  • (ArgumentError)


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

def check_validity!
  return true if AVAILABLE_CHECKS.any? { |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

#content_size_valid?(file_size, flat_options) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#max_size(flat_options) ⇒ Object



56
57
58
# File 'lib/active_storage_validations/size_validator.rb', line 56

def max_size(flat_options)
  flat_options[:between]&.max || flat_options[:less_than] || flat_options[:less_than_or_equal_to]
end

#min_size(flat_options) ⇒ Object



52
53
54
# File 'lib/active_storage_validations/size_validator.rb', line 52

def min_size(flat_options)
  flat_options[:between]&.min || flat_options[:greater_than] || flat_options[:greater_than_or_equal_to]
end

#validate_each(record, attribute, _value) ⇒ Object



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

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?
  flat_options = unfold_procs(record, self.options, AVAILABLE_CHECKS)

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

    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))

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