Class: HC::Validators::ClassValidator

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

Overview

Allows for ActiveRecord validation of class types

Instance Method Summary collapse

Instance Method Details

#error(record, attribute) ⇒ Object



23
24
25
# File 'lib/hc/validators/class.rb', line 23

def error(record, attribute)
  record.errors.add(attribute, options[:message] || generate_message)
end

#generate_messageObject



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/hc/validators/class.rb', line 27

def generate_message
  if options[:is_a]
    "must be a #{options[:is_a]}"
  elsif options[:in]
    "must be one of: #{options[:in]}"
  elsif options[:array_of]
    "must be an array of #{options[:array_of]}"
  else
    :invalid
  end
end

#validate_each(record, attribute = nil, value = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/hc/validators/class.rb', line 10

def validate_each(record, attribute = nil, value = nil)
  options = default_options.merge(self.options)
  if options[:is_a]
    validate_one(options, record, attribute, value)
  elsif options[:in]
    validate_in(options, record, attribute, value)
  elsif options[:array_of]
    validate_array(options, record, attribute, value)
  else
    raise 'Invalid validation options'
  end
end