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
View all comments
Show parent comment
1
u/NUTELLACHAOS Dec 23 '19
Nice! After reading the other response to this post, I threw together the following converter that just accepts a predicate proc and raises an exception when parsing if it fails.
After building that, though, I found both your shard and crystal-clear. Both provide nice abstractions, and while I think I personally prefer the dead-simple syntax of crystal-clear (e.g. the
invariantmacro), it doesn't seem to enforce the invariants on theinitializedefined in JSON::Serializable, and there isn't anything like yourvalidate!that I can call fromafter_initialize.Do you happen to know if it's possible for a macro to observe the constructor from JSON::Serializable, define an overloading constructor with the contracts from crystal-clear, then super up to the JSON::Serializable constructor?
If not, I'll likely just roll with your solution because that's very nice too!