Define Class object validations

76 Views Asked by At

Is there a native way to define validations for a Crystal object ? Let's consider this class:

class Person

  def initialize(@age : Int32) 

  end

end

How could I add a simple validation if age < 18 ? Ex:

Person.new(10)
>> Error: attibute 'age' should be greater than 18

I saw a 3rd party library doing this but I'd like to avoid adding dependencies.

1

There are 1 best solutions below

0
On BEST ANSWER

There is no automated way to achieve runtime validation, but there is an idiomatic way:

def initialize(@age)
  raise ArgumentError.new("age must be 18 or more") if @age < 18
end