Producing JSON Arrays in Ruby
14 Jun 2016I’ve been working on a project and building the backend with Ruby and Sinatra. So far so good, until I wanted to take a list of objects I fetched from ActiveRecord and produce a JSON array. I had a function set up to JSONify a single object:
Extending this to produce a JSON array for a bunch of model objects is simple for anyone who is familiar with Ruby…. Something I’m clearly not! Here’s the clean solution I eventually got:
For the laughs (and sadness), here was my initial (and ghetto) implementation of to_json_list:
Replacing the above method with the single-line version felt almost as good as removing that # Ghetto comment!