When to use Serializers?
Define Serializer
Serialisation (I’ll use s in writing about the concept, and z when discussing the thing itself) in programming is about converting the state of an object into something that can be stored or transferred. When you really want to serialise the state of an application to disk, you probably want full, unmodified serialisation, so the question about serialisation typically comes up when you want to share data with external parties. To these parties you don’t want to share the raw data, but pre-process it a bit, perhaps convert the internal state to objects that are more generic and don’t expose the full internals. In such case you might want to consider introducing the concept of Serializers.
Alternatives to using serializers
Before introducing new tooling, always consider the following default options Rails offers:
- Serializers live on the view-layer. The default approach rails suggests is to have e.g.
{index, show}.json.jbuilderfiles in your view directory. The nice thing about jbuilder (in contrast to erb, which, in theory, you could also use to serialise data), is that these files support full ruby. But these files easily get wieldy when you want to transform your data in more complicated ways.- The equivalent of jbuilder for xml is builder
- An even more lightweight approach in Rails for json is simply to do something like
render json: @user.as_json(only: [:name, :email])directly in your controllers, but if .jbuilder doesn’t scale for you, this definitely won’t work for you.
Use serializers when your result objects become more complicated
Serializers will help you responding using:
- Standardized responses (e.g. JSON-API)
- Allow for (perhaps even conditionally) include associations
- …
In closing: anti-patterns
- Create PORO (Plain Old Ruby Objects) and all call them ‘a model’ => It is fine to use PORO instead of off the shelf gems, but if you use it for serialisation, call it serialisation.
- A lot of processing in controllers / views