Class: ActiveStorageValidations::LimitValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Includes:
ErrorHandler, OptionProcUnfolding, Symbolizable
Defined in:
lib/active_storage_validations/limit_validator.rb

Overview

:nodoc:

Constant Summary collapse

AVAILABLE_CHECKS =
%i[max min].freeze

Instance Method Summary collapse

Methods included from ErrorHandler

#add_error, #initialize_error_options

Methods included from OptionProcUnfolding

#unfold_procs

Instance Method Details

#check_validity!Object



13
14
15
16
17
# File 'lib/active_storage_validations/limit_validator.rb', line 13

def check_validity!
  unless AVAILABLE_CHECKS.any? { |argument| options.key?(argument) }
    raise ArgumentError, 'You must pass either :max or :min to the validator'
  end
end

#files_count_valid?(count, flat_options) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
33
34
35
36
37
38
# File 'lib/active_storage_validations/limit_validator.rb', line 30

def files_count_valid?(count, flat_options)
  if flat_options[:max].present? && flat_options[:min].present?
    count >= flat_options[:min] && count <= flat_options[:max]
  elsif flat_options[:max].present?
    count <= flat_options[:max]
  elsif flat_options[:min].present?
    count >= flat_options[:min]
  end
end

#validate_each(record, attribute, _) ⇒ Object



19
20
21
22
23
24
25
26
27
28
# File 'lib/active_storage_validations/limit_validator.rb', line 19

def validate_each(record, attribute, _)
  files = Array.wrap(record.send(attribute)).reject { |file| file.blank? }.compact.uniq
  flat_options = unfold_procs(record, self.options, AVAILABLE_CHECKS)
  errors_options = initialize_error_options(options)
  errors_options[:min] = flat_options[:min]
  errors_options[:max] = flat_options[:max]

  return true if files_count_valid?(files.count, flat_options)
  add_error(record, attribute, :limit_out_of_range, **errors_options)
end