Some of the most widely used JSON Templates are tequila, json_builder, argonaut few of them. But why are they getting famous day-by-day? Why it is not advisable to use to_json in your Rails Application? Why many JSON templates are gaining popularity and gradually reducing the default to_json option that is by default provided by Rails framework?
Let’s find answer to these questions and see advantages of using JSON templates over to_json.
- APIs, in most scenarios are agile and intuitive. It can be a cumbersome to send a lot of data in response (including various keys, includes, excludes, methods).
- If your schema is not deeply coupled with your API output, well then touble in knocking at your door. This can be seen if you are creating some public APIs.
- Another issue which you’ll face if you use to_json in your code is that if you want to include different API output options in different API responses, then it’s not possible. It is restrictive as well as verbose.
- Pushing representational logic into model domain is always a bad idea and may backfire in lots of ways. Like when you you want a different representation of same model in some other part of your app, or when you realize that some third-party code depends on methods you’ve overridden.
- JSON templates on the other hand, allows you to use the view context with all its power, helpers and accessing the controller state
- Sometimes your json view doesn’t even represent a single model or collection of models. In complex apps you may want to render a json representation of current state that may consist of lots of variables, components, models, and their relations. Here JSON templates come into rescue.
- Another disadvantage of using to_json is that the model and/or controller gets filled with tons of json specific details that have nothing to do with model or business logic. In fact, these JSON responses doesn’t seem to belong in the model or the controller at all and clutters up our code. According to MVC these details of the response seems much more appropriate in a view of some kind.
- If you are stuck in such a scenario where attributes defined in the schema to be renamed or modified for the representation, or we wanted to omit attributes, or we wanted to include attributes if a condition was met then using to_json is the headache.
- To handle polymorphic associations in a clean and easy way, json is not we are looking for.
- Its easy to write maintainable code in we use one of the JSON templates.
Although, the are various reasons to choose json templates, there are demerits as well. Though it’s easy its easy to write maintainable code with them, but it’s slow.
A good option that can be explored for json template is RABL gem. You can try and let me know.
Happy Coding 🙂