Class: Eaternet::ValidatedObject::TypeValidator

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

Overview

A custom validator which ensures an object is a certain class. It's here as a nested class in Eaternet::ValidatedObject for easy access by subclasses.

Examples:

Ensure that weight is a floating point number

class Dog < ValidatedObject
  attr_accessor :weight
  validates :weight, type: Float
end

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ nil

Returns:

  • (nil)


72
73
74
75
76
77
78
79
# File 'lib/eaternet/validated_object.rb', line 72

def validate_each(record, attribute, value)
  expected = options[:with]
  actual = value.class
  return if actual == expected

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