Class: ActiveStorageValidations::SizeValidator
Overview
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
#add_error, #initialize_error_options
#unfold_procs
Instance Method Details
#check_validity! ⇒ Object
28
29
30
31
32
|
# File 'lib/active_storage_validations/size_validator.rb', line 28
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
|
#content_size_valid?(file_size, flat_options) ⇒ Boolean
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
# File 'lib/active_storage_validations/size_validator.rb', line 58
def content_size_valid?(file_size, flat_options)
return false if file_size < 0
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
78
79
80
|
# File 'lib/active_storage_validations/size_validator.rb', line 78
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
74
75
76
|
# File 'lib/active_storage_validations/size_validator.rb', line 74
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
# File 'lib/active_storage_validations/size_validator.rb', line 34
def validate_each(record, attribute, _value)
return true unless record.send(attribute).attached?
files = Array.wrap(record.send(attribute))
errors_options = initialize_error_options(options)
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))
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
|