Class: ClassValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/thingtank/validators.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, values) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/thingtank/validators.rb', line 21

def validate_each(record, attribute, values)
  case values
  when NilClass
    return nil
  when Array
    if options[:with] && options[:with] == Array
      validate_single_class(record, attribute, values, options)
    else
      values.each do |value|
        validate_single_class(record, attribute, value, options)
      end
    end
  else
    validate_single_class(record, attribute, values, options)
  end
end

#validate_single_class(record, attribute, values, options) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/thingtank/validators.rb', line 2

def validate_single_class(record, attribute, values, options)
  if options[:in] # validates :hosting_account, :class => [Hash, String]
    valid = false
    options[:in].each do |klass|
      if values.is_a?(klass)
        valid = true
      end
    end
    unless valid
      record.errors.add attribute, "invalid class is #{values.class.to_s}, should be one of #{options[:in].join(', ')}"
    end
  else # validates :hosting_account, :class => Hash
    unless values.is_a?(options[:with])
      record.errors.add attribute, "invalid class is #{values.class.to_s}, should be #{options[:with]}"
    end
  end
end