Class: ValidatedObject::Base::TypeValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Extended by:
T::Sig
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.)

Automatically used in a type validation:

Examples:

Ensure that weight is a number

class Dog < ValidatedObject::Base
  attr_accessor :weight, :neutered
  validates :weight, type: Numeric  # Typed and required
  validates :neutered, type: Boolean, allow_nil: true  # Typed but optional
end

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



116
117
118
119
120
121
122
123
124
125
# File 'lib/validated_object.rb', line 116

def validate_each(record, attribute, value)
  validation_options = T.let(options, SymbolHash)

  expected_class = validation_options[:with]

  return if pseudo_boolean?(expected_class, value) ||
            expected_class?(expected_class, value)

  save_error(record, attribute, value, validation_options)
end