Live Streaming

To see how streaming works, let’s create a controller called LiveAssetsController at app/controllers/live_assets_controller.rb that includes the ActionController::Live functionality and streams “hello world” continuously:

live_assets/1_live/app/controllers/live_assets_controller.rb
 
class​ LiveAssetsController < ActionController::Base
 
include ActionController::Live
 
 
def​ hello
 
while​ true
 
response.stream.write ​"Hello World\n"
 
sleep 1
 
end
 
rescue​ IOError
 
response.stream.close
 
end
 
end

Our controller provides an action named hello that streams Hello World every second. If, for any reason, the connection between the server and the client drops, response.stream.write will fail with IOError, which we ...

Get Crafting Rails 4 Applications, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.