Class: ActiveStorageValidations::LimitValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Includes:
OptionProcUnfolding
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 OptionProcUnfolding

#unfold_procs

Instance Method Details

#check_validity!Object

Raises:

  • (ArgumentError)


9
10
11
12
# File 'lib/active_storage_validations/limit_validator.rb', line 9

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

#files_count_valid?(count, flat_options) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
30
31
32
33
# File 'lib/active_storage_validations/limit_validator.rb', line 25

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



14
15
16
17
18
19
20
21
22
23
# File 'lib/active_storage_validations/limit_validator.rb', line 14

def validate_each(record, attribute, _)
  return true unless record.send(attribute).attached?

  files = Array.wrap(record.send(attribute)).compact.uniq
  flat_options = unfold_procs(record, self.options, AVAILABLE_CHECKS)
  errors_options = { min: flat_options[:min], max: flat_options[:max] }

  return true if files_count_valid?(files.count, flat_options)
  record.errors.add(attribute, options[:message].presence || :limit_out_of_range, **errors_options)
end