Live Streaming [Rails 4 Countdown to 2013]

Posted on

This post is part of a series of 31 Rails 4 articles being released each day in December 2012.

One major feature being added to Rails 4 is the ability to stream data to the client. While the streaming of templates is currently available in Rails 3, thanks to Aaron Patterson's efforts, we can now stream other types of data such as JSON.

To enable live streaming in a controller, you must mixin the module ActionController::Live. This provides an I/O like interface to the response, allowing you to continuously write to the client until the stream is explicitly closed.

Here is an example of a live streaming controller from the Rails docs:

class MyController < ActionController::Base
  include ActionController::Live

  def stream
    response.headers['Content-Type'] = 'text/event-stream'
    100.times {
      response.stream.write "hello world\n"
      sleep 1
    }
    response.stream.close
  end
end

Requirements

  • All actions executed from ActionController::Live enabled controllers are run in a separate thread, thus controller action code must be thread safe.
  • A concurrent Ruby Web Server is required to take advantage of live streaming. Be sure to take a look at puma.
  • Headers must be written before anything is written to the client.
  • Streams must be closed.

Why is this important?

This feature alone allows Rails to do more than just serve HTTP web pages and JSON. It can now handle a variety of other use cases, that were not possible in the past. For example, using Server-sent events, the ability to create chat clients, push notifications, and real-time feeds are achievable from Rails itself.

Further Reading

002

This post is by Kevin Faustino. Kevin is the Chief Craftsman of Remarkable Labs and also the founder of the Toronto Ruby Brigade.


Comments

comments powered by Disqus