sse-rails is a simple wrapper around ActionController::Live to hide all the complexity of streaming.
Installation
Add this line to your application's Gemfile:
gem 'sse-rails'And then execute:
$ bundleOr install it yourself as:
$ gem install sse-railsUsage
Add these lines to a controller:
require 'rails/sse'
include ActionController::Live
include Rails::SSEAnd then use it in one of your actions:
def listen
stream do |channel|
channel.post({ username: 'jim' }, event: 'refresh')
end
endYou can also use Rails::SSE::Channel#ping! to see if connection is still open. This is useful when you are in a loop like this:
def listen
stream do |channel|
loop do
channel.post('anything') if condition
channel.ping!
sleep 1
end
end
endWithout pinging you would know that the connection was lost only when the condition becomes true.
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request