class ValidatedObject::Base::TypeValidator
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:
@example 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
Public Instance Methods
validate_each(record, attribute, value)
click to toggle source
# 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
Private Instance Methods
boolean?(value)
click to toggle source
# File lib/validated_object.rb, line 140 def boolean?(value) value.is_a?(TrueClass) || value.is_a?(FalseClass) end
expected_class?(expected_class, value)
click to toggle source
# File lib/validated_object.rb, line 135 def expected_class?(expected_class, value) value.is_a?(expected_class) end
pseudo_boolean?(expected_class, value)
click to toggle source
# File lib/validated_object.rb, line 130 def pseudo_boolean?(expected_class, value) expected_class == Boolean && boolean?(value) end
save_error(record, attribute, value, validation_options)
click to toggle source
# File lib/validated_object.rb, line 153 def save_error(record, attribute, value, validation_options) record.errors.add attribute, validation_options[:message] || "is a #{value.class}, not a #{validation_options[:with]}" end