Rails

Streaming data with Rails > 3.1


One of the new features that shipped with Rails 3.1 was streaming support. Now, all you need is a streaming cappable 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.

Beginner
Administrate review
Beginner
Fixing Rspec and Cucumber random failures in your Continuous Integration Service
Best Practices
De Código, Café y Cervezas 07 – ¿Somos profesionales?