granola
granola copied to clipboard
RFC: Granola::Serializer#to_serializer
The idea here is to simplify including "root keys" in serialized objects. Right now, the simplest way of achieving this is by overwriting to_json and similar methods on the serializers to include an object that returns the root keys.
This is a bit messy (or at least repetitive, if you have multiple response formats / renderers in your app.)
In order to simplify this, we can add a Serializer#to_serializer method that the renderers use instead of hard-coding self. This allows users to implement the concept of a "Root" serializer that wraps the top-level serializer used in every response by simply overriding the #to_serializer method in a base serializer used throughout the app.
cc @sd
👍 / 👎?
Three thumbs up!!! 👍 👍 👍
one comment, though... do you see any other uses for to_serializer? if the only purpose is to allow the injection of a root serializer, perhaps it would be clearer if the method were called root_serializer
If the "root" serializer has to add more data, it is because you are serializing something different.
Using the User example, a list of Users is not the same as "a page of results of User", which includes more information (any combination of, current page, total elements, next page, previous page, next page marker (if "load more" instead of pages), etc). Maybe the list of results is heterogenous (lets say you are fetching all type of objects in your system with some tag "X", and the result is mixed), and in such case which serializer are you going to use to generate the "meta" data?
Each application will be different and have different needs, so I don't think it is something that the library has to solve, at least not with code. I would rather add more documentation, examples of how to solve a few common scenarios (define a pattern instead of implementing it).