Class: ActiveStorageValidations::SizeValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ActiveStorageValidations::SizeValidator
show all
- Includes:
- ErrorHandler, OptionProcUnfolding
- Defined in:
- lib/active_storage_validations/size_validator.rb
Overview
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
#add_error, #initialize_error_options
#unfold_procs
Instance Method Details
#check_validity! ⇒ Object
12
13
14
15
16
|
# File 'lib/active_storage_validations/size_validator.rb', line 12
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
41
42
43
44
45
46
47
48
49
50
51
52
53
|
# File 'lib/active_storage_validations/size_validator.rb', line 41
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
59
60
61
|
# File 'lib/active_storage_validations/size_validator.rb', line 59
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
55
56
57
|
# File 'lib/active_storage_validations/size_validator.rb', line 55
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
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
# File 'lib/active_storage_validations/size_validator.rb', line 18
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))
error_type = "file_size_not_#{flat_options.keys.first}".to_sym
add_error(record, attribute, error_type, **errors_options)
break
end
end
|