Class: ValidatedObject::Base::TypeValidator

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

Overview

A custom validator which ensures an object is an instance of a class or a subclass. It supports a pseudo-boolean class for convenient validation. (Ruby doesn’t have a built-in Boolean.)

Examples:

Ensure that weight is a number

class Dog < ValidatedObject::Base
  attr_accessor :weight, :neutered
  validates :weight, type: Numeric
  validates :neutered, type: Boolean
end

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ nil

Returns:

  • (nil)


81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/validated_object.rb', line 81

def validate_each(record, attribute, value)
  expected_class = options[:with]

  if expected_class == Boolean
    return if value.is_a?(TrueClass) || value.is_a?(FalseClass)
  else
    return if value.is_a?(expected_class)
  end

  msg = options[:message] || "is class #{value.class}, not #{expected_class}"
  record.errors.add attribute, msg
end