Class: ActionController::Live::SSE
- Inherits:
-
Object
- Object
- ActionController::Live::SSE
- Defined in:
- 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:
1) Event. If specified, an event with this name will be dispatched on
the browser.
2) Retry. The reconnection time in milliseconds used when attempting
to send the event.
3) 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 collapse
- PERMITTED_OPTIONS =
%w( retry event id )
Instance Method Summary collapse
- #close ⇒ Object
-
#initialize(stream, options = {}) ⇒ SSE
constructor
A new instance of SSE.
- #write(object, options = {}) ⇒ Object
Constructor Details
#initialize(stream, options = {}) ⇒ SSE
Returns a new instance of SSE.
112 113 114 115 |
# File 'lib/action_controller/metal/live.rb', line 112 def initialize(stream, = {}) @stream = stream @options = end |
Instance Method Details
#close ⇒ Object
117 118 119 |
# File 'lib/action_controller/metal/live.rb', line 117 def close @stream.close end |
#write(object, options = {}) ⇒ Object
121 122 123 124 125 126 127 128 |
# File 'lib/action_controller/metal/live.rb', line 121 def write(object, = {}) case object when String perform_write(object, ) else perform_write(ActiveSupport::JSON.encode(object), ) end end |