Class: ActiveStorageValidations::SizeValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ActiveStorageValidations::SizeValidator
- 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
- #check_validity! ⇒ Object
- #content_size_valid?(file_size, flat_options) ⇒ Boolean
- #max_size(flat_options) ⇒ Object
- #min_size(flat_options) ⇒ Object
- #validate_each(record, attribute, _value) ⇒ Object
Methods included from OptionProcUnfolding
Instance Method Details
#check_validity! ⇒ Object
11 12 13 14 |
# File 'lib/active_storage_validations/size_validator.rb', line 11 def check_validity! return true if AVAILABLE_CHECKS.any? { |argument| .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
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, ) if [:between].present? [:between].include?(file_size) elsif [:less_than].present? file_size < [:less_than] elsif [:less_than_or_equal_to].present? file_size <= [:less_than_or_equal_to] elsif [:greater_than].present? file_size > [:greater_than] elsif [:greater_than_or_equal_to].present? file_size >= [: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() [:between]&.max || [:less_than] || [: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() [:between]&.min || [:greater_than] || [: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)) = {} [:message] = [:message] if [:message].present? = unfold_procs(record, self., AVAILABLE_CHECKS) files.each do |file| next if content_size_valid?(file.blob.byte_size, ) [:file_size] = number_to_human_size(file.blob.byte_size) [:min_size] = number_to_human_size(min_size()) [:max_size] = number_to_human_size(max_size()) record.errors.add(attribute, :file_size_out_of_range, **) break end end |