0

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.

Graham Slick
  • 6,692
  • 9
  • 51
  • 87
  • I think this is too broad. What would you like the validations to do? – mgarciaisaia Dec 22 '16 at 20:33
  • It's a simple example that would help me achieve more advanced stuff but I want to make it easy to give an answer as per SO standards. But I'm editing my answer with an example – Graham Slick Dec 22 '16 at 20:34

1 Answers1

3

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 
Julien Portalier
  • 2,959
  • 1
  • 20
  • 22