t6d / smart_properties

Ruby accessors on steroids
MIT License
177 stars 20 forks source link

Support validation before and after conversion #37

Open t6d opened 8 years ago

t6d commented 8 years ago

In some scenarios, it might be necessary to perform validation before performing the conversion. This is currently unsupported.

fabrik42 commented 8 years ago

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:

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.

benedikt commented 8 years ago

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:

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)

fabrik42 commented 8 years ago

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.

t6d commented 8 years ago

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..

t6d commented 8 years ago

By the way, I can highly recommend using dedicated objects for complex validation and conversion operations: SmartProperties advanced input validation.

fabrik42 commented 8 years ago

:+1: