carlesjove / collection_json_serializer

A Ruby gem to respond with Collection+JSON
MIT License
3 stars 1 forks source link

Refactor validations process #41

Open carlesjove opened 9 years ago

carlesjove commented 9 years ago

Validation is an important part of CJ::S, but it has too much code and repetition at the moment. A new validation process should be done in 2 clear, distinguished steps:

1. Spec/Extensions validation

Serializers' attributes should be validated against CJ's Spec. If a serializer uses extensions, it should be validated against the result of merging the extension spec with Spec. Two steps to be taken:

  1. The absence of required attributes/objects by the spec and declared extensions, should raise an error and stop the process.
  2. The presence of attributes/objects in the serializer that are not part of the spec or the declared extensions should raise an error and stop the process. If :open_attrs extension is used, this step shall be skipped.
    Important!

Extensions must not have the capacity to remove attributes/objects from the Spec. They just can add to it.

2. Data type validation

Data type of each field must be validated against the spec. Instead of having this validation done in multiple methods, it should be done by a single method that goes through each attribute and performs a validation.

This could be specified at the Spec/Extension level:

module Spec
  DEFINITION = {
    href: {
      meta: {
        validates_as: :url
      }
    }
  }

Unless specified, the default validation as VALUE will apply.

Note:

The trickier part of this may be setting the correct path for the error message.

carlesjove commented 9 years ago

Validations is one of the most complicated and code consuming process at the moment. This is because everything is being validated: collection properties and all values.

I was just thinking: do we really need to validate data coming from the model? Wouldn't it make more sense to simply return data in the expected/valid format, instead of passing the load to the model?

Example: if a model attribute returns a regex, now an error would be raised. Instead of asking for a string, CJ::S should just return this regex as a string.

The idea behing this is that CJ::S mission should be building valid CJ responses, not requiring model data to match CJ's spec.