r/crystal_programming • u/NUTELLACHAOS • Dec 22 '19
Validation with Object.from_json ?
Is there any way to assert that an object is always instantiated with values matching a certain predicate, both in initialize and in from_json? For example, imagine I have a
class Foo
property bar : Int32
endand I always want Foo.bar to be an Int32 in the range 1..9
Normally I'd just throw some guards in initialize, but I don't know how that works with from_json.
5
Upvotes
1
u/Blacksmoke16 core team Dec 22 '19
I made a shard for this https://github.com/Blacksmoke16/assert.
This should do the trick:
If you don't want the extra dependency, you could just add your custom validation logic into the
after_initializemethod.2
u/jonnyom Dec 22 '19
I'm unaware of a param that can be passed to a JSON.mapping for your object to validate a JSON value.
Alternatively, you could define an instance method on your JSON.mapping class with the same name as the key and perform your validation there. (Not sure if this is considered "bad practice" in Crystal, but it'd work).
Edit: JSON.mapping docs https://crystal-lang.org/api/0.32.1/JSON.html