smart_properties icon indicating copy to clipboard operation
smart_properties copied to clipboard

Support validation before and after conversion

Open t6d opened this issue 9 years ago • 6 comments

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

t6d avatar Jan 17 '16 17:01 t6d

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.

fabrik42 avatar Jan 18 '16 09:01 fabrik42

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 in accepts

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)

benedikt avatar Jan 18 '16 10:01 benedikt

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.

fabrik42 avatar Jan 18 '16 11:01 fabrik42

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 avatar Jan 22 '16 16:01 t6d

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

t6d avatar Jan 22 '16 16:01 t6d

:+1:

fabrik42 avatar Jan 22 '16 16:01 fabrik42