Class: ActiveStorageValidations::SizeValidator
- Inherits:
-
ActiveModel::EachValidator
- Object
- ActiveModel::EachValidator
- ActiveStorageValidations::SizeValidator
- 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) ⇒ Boolean
- #validate_each(record, attribute, _value) ⇒ Object
Instance Method Details
#check_validity! ⇒ Object
9 10 11 12 13 |
# File 'lib/active_storage_validations/size_validator.rb', line 9 def check_validity! return true if AVAILABLE_CHECKS.any? { |argument| .key?(argument) } raise ArgumentError, 'You must pass either :less_than, :greater_than, or :between to the validator' end |
#content_size_valid?(file_size) ⇒ Boolean
33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/active_storage_validations/size_validator.rb', line 33 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 |
#validate_each(record, attribute, _value) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/active_storage_validations/size_validator.rb', line 15 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? files.each do |file| next if content_size_valid?(file.blob.byte_size) [:file_size] = number_to_human_size(file.blob.byte_size) record.errors.add(attribute, :file_size_out_of_range, ) break end end |