I want to render a list of objects into JSON, but I don’t want to user to_json because I want to render a very specific format and subset of information.
This is my view (foo.json.erb):
{
"id" : <%= @user.id %>,
"progress" : [
<% @rewards_tapped[0..-2].each do |reward| %>
<%= render "rewardprogress", :reward => reward,
:user => @user %>,
<% end %>
<%= render "rewardprogress", :reward => @rewards_tapped.last,
:user => @user %>
]
}
As you can see, it is pretty ugly because I have to render the last item in @rewards_tapped separately so that it does not have a comma after the entry (to make valid JSON).
There has to be a better way to do this, I’m just a bit new to Ruby. Can someone point me in the right direction?
If you don’t require incremental rendering, then you could simply build up a nested hash/array Ruby data structure, and call
#to_jsonon that. You can also use symbols as keys, and they’ll become string keys in the resulting JSON.Assuming you do need the incremental rendering, then this might be a minor improvement you could make (or might just be replacing one kind of ugly with another). This might be faster though if converting
@rewards_tappedto an array for[0..-2]is at all slow.