Streaming Data With Rails > 3.1

Reading Time: < 1 minutes

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
Read More

Data Encryption with Rails 7

Reading Time: 4 minutes There are massive amounts of sensitive information managed and stored online in the cloud or connected servers. Encryption…