A few weeks ago I faced with a requirement to optimize a huge JSON response from Rails-based API.
For example, we want to respond large set of data as JSON collection. In our controller, we have some action for that, but rails Live API couldn’t stream JSON or XML directly. But we can use a little trick.

1
2
3
4
5
6
7
class PostsController
  def index 
    @data = Post.order(:created_at) # Or other scope or service object.
    @last_item = @data.last
    render stream: true, layout: false, content_type: 'application/json'
  end 
end  

and use good old ERB (index.erb) for the index action:

1
2
3
4
5
6
[
  <% @data.find_each do |item| %>
    <%= raw item.to_json %> 
    <%= ', ' unless item == @last_item %>
  <% end %>
]

Here we use batch loading find_each for the @data scope and we need last item ofcourse.