Class: ActiveStorageValidations::LimitValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active_storage_validations/limit_validator.rb

Overview

:nodoc:

Constant Summary collapse

AVAILABLE_CHECKS =
%i[max min].freeze

Instance Method Summary collapse

Instance Method Details

#check_validity!Object

Raises:

  • (ArgumentError)


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

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) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#validate_each(record, attribute, _) ⇒ Object



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

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

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

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