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}" 

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}"

Then, in our controller action:

self.response_body = Streamer.new

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

Know more about us!

Best Practices
Approaching Rails Legacy Systems – Chapter 1: Project Anatomy
PDF and XLSX reports with Ruby on Rails.
Advanced Level
Fixing Rspec and Cucumber random failures in your Continuous Integration Service
Copy link
Powered by Social Snap