Class: ArrayValidatorBase

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active_model_validators_ex/array_validator_base.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ ArrayValidatorBase

Returns a new instance of ArrayValidatorBase.



2
3
4
5
6
7
# File 'lib/active_model_validators_ex/array_validator_base.rb', line 2

def initialize(options)
  options[:allow_nil]   ||= false
  options[:allow_blank] ||= false

  super(options)
end

Instance Method Details

#custom_validations(record, attribute, value) ⇒ Object



32
33
34
# File 'lib/active_model_validators_ex/array_validator_base.rb', line 32

def custom_validations(record, attribute, value)
  raise 'override this method to perform custom validations'
end

#validate_each(record, attribute, value) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/active_model_validators_ex/array_validator_base.rb', line 9

def validate_each(record, attribute, value)
  # TODO: extract this to a more generic class instad of ArrayValidatorBase
  return if (options[:allow_blank] && value.blank?) ||
            (options[:allow_nil] && value.nil?)

  if !options[:allow_blank] && value.blank?
    record.errors.add(attribute, :blank, options)
    return
  end

  if !options[:allow_nil] && value.nil?
    record.errors.add(attribute, :nil, options)
    return
  end

  unless value.is_a? Array
    record.errors.add(attribute, :array, options)
    return
  end

  custom_validations(record, attribute, value)
end