Streaming Data With Rails > 3.1

Reading Time: < 1 minute

One of the new features that shipped with Rails 3.1 was streaming support. Now, all you need is a streaming capable server like unicorn or thin and add this line in your controller action:

render stream: true

Done. However, something is wrong with this. It only works with templates, what if you want to stream a big xml or csv file?, in Rails versions before 3.1 we were able to do this sending a proc or lambda in the response body, something like this:

self.response_body = ->(response, output) do
  100.times do |n|
    output.write "streaming #{n}" 
  end
end

Sending a proc in the response body is deprecated in Rails 3.1, and there isn't much documentation about how to achieve this in Rails > 3.1. The solution I found works at rack level, based on the rack source we only need to send an Enumerator object that responds to each in the response body, and wrap the streaming logic in it, something like this:

class Streamer
  def each
    100.times do |n|
      yield "streaming #{n}"
    end 
  end
end

Then, in our controller action:

self.response_body = Streamer.new

And, thats it!, simple streaming in your rails application.

Know more about us!

0 Shares:
You May Also Like
RailsConf 2017 Adventure
Read More

RailsConf 2017 Adventure

Reading Time: 3 minutes Hello, I want to talk to you about my visit to the city of Phoenix Arizona, where I…

Fake it!

Reading Time: 3 minutes Fake It! A couple of tools to generate fake data in your app. Hi, this time I want…