Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Websocket on Rails

Websocket on Rails

Short showcase how to use the awesome websocket technology in a Rails project using websocket-rails

Jeroen Rosenberg

September 07, 2012
Tweet

More Decks by Jeroen Rosenberg

Other Decks in Programming

Transcript

  1. Introducing websocket-rails 1. echo "gem 'thin'" >> Gemfile 2. echo

    "gem 'websocket-rails'" >> Gemfile 3. bundle install 4. rails g websocket_rails:install
  2. 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
  3. 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
  4. 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
  5. Use complex messages and channels (1) class RsvpController < WebsocketRails::BaseController

    ... def rsvp @rsvp_yes_count += 1 if message[:attending] rsvp = { :yes => @rsvp_yes_count } WebsocketRails[:rsvp].trigger 'new', rsvp end end
  6. Use complex messages and channels (2) $ -> dispatcher =

    new WebSocketRails('localhost:3000/websocket') $('#rsvp_yes').bind 'click', (message) => rsvp = attending: true dispatcher.trigger 'rsvp.new', rsvp channel = dispatcher.subscribe 'rsvp' channel.bind 'new', (rsvp) => $('#rsvp_yes_count').html rsvp.yes
  7. References Websocket spec • http://dev.w3.org/html5/websockets/ Websocket-rails project page • http://danknox.github.com/websocket-rails/

    My project • https://github.com/jeroenr/followup Ruby eventmachine • http://rubyeventmachine.com/