smart_properties
smart_properties copied to clipboard
Support validation before and after conversion
In some scenarios, it might be necessary to perform validation before performing the conversion. This is currently unsupported.
Example use case: I want to use a smart properties class to validate/handle a ISO8601 date string.
So I want smart_properties to do the following:
- Check the input, that it is a valid ISO8601 string (not implemented yet)
- Convert the string to a ruby Date object (currently
converts
) - Make sure, that it is a Date object (currently
accepts
)
In this case, you need to check accepts
before the converts
- otherwise it could lead to a date parser error, in case the date string is not valid.
While I understand that having this as a core feature would be nice, I can think of two other ways to implement this without the need for a core feature:
- Just raise an exception in the converter method (
accepts
would raise anyways) - Let the converter return
nil
or something else to indicate that converting failed and check for that value inaccepts
If I understand it correctly, you'd nonetheless need both a accept before and after the conversion. Just because the string has a valid format, doesn't necessarily mean that the value makes any sense (think leap years)
In my specific use case, I don't want to raise an exception. The whole point of the class would be to validate/prepare a combination of given params. If it raises, I would need another layer above the class to handle these exceptions.
I don't want the converter to return nil
, because this would basically move the validation logic into the converter and I can not determine, if the input was just invalid or not given at all.
I personally think that smart_properties can become very handy for input validation - but in real world scenarios with user input, we should have one more callback before the converter to make sure the converter does not crash.
There is no harm in adding a prepares
hook, so that the execution order would be prepares -> converts -> accepts
. I'll actually try and release this as a feature to SmartProperties v1.x.
.
By the way, I can highly recommend using dedicated objects for complex validation and conversion operations: SmartProperties advanced input validation.
:+1: