This document introduces websocket-rails, a gem for building real-time web applications using websockets in Ruby on Rails. It allows asynchronous full-duplex communication by using websockets instead of traditional HTTP requests. The gem maps websocket events to controller actions, and controllers can then trigger events that are broadcast to clients. This enables features like pushing new data to only interested clients in real-time. Code examples demonstrate setting up websocket-rails, defining event mappings and controllers, and binding to events from the client-side.
18. Map events to controller actions
WebsocketRails::EventMap.describe do
# You can use this file to map incoming events to controller
actions.
# One event can be mapped to any number of controller
actions. The
# actions will be executed in the order they were subscribed.
namespace :rsvp do
subscribe :new, :to => RsvpController, :with_method => :
rsvp
end
end
19. Use rails-like controllers
class RsvpController < WebsocketRails::BaseController
def initialize_session
# initialize application scoped variables here
@rsvp_yes_count = 0
end
def rsvp
@rsvp_yes_count += 1 if message
broadcast_message :new_rsvp, @rsvp_yes_count
end
end
20. Trigger and bind to events in the
client
$ ->
dispatcher = new WebSocketRails('localhost:3000/websocket')
dispatcher.on_open = (data) ->
console.log "Connection has been established: #{data}"
$('#rsvp_yes').bind 'click', (message) =>
dispatcher.trigger 'rsvp.new', true
dispatcher.bind 'new_rsvp', (rsvp_yes_count) =>
$('#rsvp_yes_count').html rsvp_yes_count