As the web continues to mature, JSON APIs (and XML if you’re into that) have become increasingly important. But if you’ve tried to use Rails to write an API recently, you know there are a handful of competing methods and gems focused on making this better. I’m all for interchangable libraries, but, as Yehuda Katz pointed out in his recent talk at RailsConf, Rails needs a “convention over configuration” approach to solving the JSON serialization problem once and for all. So I was pretty excited when I heard about Jose Valim’s ActiveModel::Serializer.
Instead of dealing with JSON views or presenters, ActiveModel::Serializer adds a new layer between rendering JSON in a controller and defining a custom to_json method. Now when rendering JSON in a controller Rails will look for a Serializer for the matching model and defer to that for generating the payload. Here are some examples to get you up and running.
We can start with a really simple Cat model.
Now lets write a controller action. Not really anything exciting yet.
OK so here’s where the magic happens. Let’s say we want to change up the JSON a little bit. For example we want to include the owner’s attributes as well. Well that’s super easy. Just make a CatSerializer in app/serializers like this.
Now look how our JSON response has changed!
This isn’t a very radical change in how some of the other decorator gems work, but I think it does a really good job at making serialization a first class citizen. Also the fact that it was built by 2 Rails core members probably gives it the best chance for some day being included in all Rails apps be default. Now they just need to convince DHH that it’s a better approach than using JSON views with Jbuilder. :P