Showing posts from August, 2017

Better Ruby serialization into JSON

JsonDumper Serialize Ruby into JSON. Cleaner. Faster. Rails is at its best when it comes to convention over configuration. Responders gem provides a nice way to serialize ruby objects into json using Object#as_json . Unfortunately this style of serialization crumbles when your app needs to present the same resource in different views, to different users with different permissions. Of course we have jBuilder. But if you ask me its DSL looks a bit ugly and not intuitive. Also it cannot eager load needed associations so you have to handle this burden yourself. In this article I am going to explain how to work with JsonDumper gem which hopefully solves former problems. Its main goals are: help serialize Ruby objects and ActiveRecord objects into json help organize your code solve N+1 query problem Usage Let's say you want to serialize Human object, which has many Cars. First define a class that is going to serialize Human: class