websocket on rails

Post on 19-May-2015

8.101 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

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

TRANSCRIPT

Websocket on railsBuilding realtime webapps

I'm a Java Developer who likes to ride the rails!

The future is now!

What's so great about Websocket?

HTTP is half-duplex

Asynchronous full-duplex communicationWebsocket is asynchronous & full-duplex

So, a little less of this...

So instead of this...

Or this...

Or this...

You tell me... what's new?

Push

So, how to ride the rails with this?

Introducing websocket-rails

1. echo "gem 'thin'" >> Gemfile2. echo "gem 'websocket-rails'" >> Gemfile3. bundle install4. rails g websocket_rails:install

Ruby eventmachine

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 endend

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 endend

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

Broadcast to anyone out there, or...

...only push to whom is interested

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 endend

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

Dem

o

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/

top related