123456789_123456789_123456789_123456789_123456789_

Class: ActionController::Live::SSE

Relationships & Source Files
Inherits: Object
Defined in: actionpack/lib/action_controller/metal/live.rb

Overview

Action Controller Live Server Sent Events

This class provides the ability to write an SSE (Server Sent Event) to an ::IO stream. The class is initialized with a stream and can be used to either write a JSON string or an object which can be converted to JSON.

Writing an object will convert it into standard SSE format with whatever options you have configured. You may choose to set the following options:

:event : If specified, an event with this name will be dispatched on the browser.

:retry : The reconnection time in milliseconds used when attempting to send the event.

:id : If the connection dies while sending an SSE to the browser, then the

server will receive a {Last-Event-ID} header with value equal to {id}.

After setting an option in the constructor of the SSE object, all future SSEs sent across the stream will use those options unless overridden.

Example Usage:

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

  def index
    response.headers['Content-Type'] = 'text/event-stream'
    sse = SSE.new(response.stream, retry: 300, event: "event-name")
    sse.write({ name: 'John'})
    sse.write({ name: 'John'}, id: 10)
    sse.write({ name: 'John'}, id: 10, event: "other-event")
    sse.write({ name: 'John'}, id: 10, event: "other-event", retry: 500)
  ensure
    sse.close
  end
end

Note: SSEs are not currently supported by IE. However, they are supported by Chrome, Firefox, Opera, and Safari.

Constant Summary

Class Method Summary

Instance Method Summary

Constructor Details

.new(stream, options = {}) ⇒ SSE

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/live.rb', line 115

def initialize(stream, options = {})
  @stream = stream
  @options = options
end

Instance Method Details

#close

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/live.rb', line 120

def close
  @stream.close
end

#perform_write(json, options) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/live.rb', line 134

def perform_write(json, options)
  current_options = @options.merge(options).stringify_keys

  PERMITTED_OPTIONS.each do |option_name|
    if (option_value = current_options[option_name])
      @stream.write "#{option_name}: #{option_value}\n"
    end
  end

  message = json.gsub("\n", "\ndata: ")
  @stream.write "data: #{message}\n\n"
end

#write(object, options = {})

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/live.rb', line 124

def write(object, options = {})
  case object
  when String
    perform_write(object, options)
  else
    perform_write(ActiveSupport::JSON.encode(object), options)
  end
end