elcuervo's nest

Easy websockets with Cuba

Websockets

I have the urge to find simple solutions to complex problems, in that mad quest i've found myself reading extremely long libraries that do things in complicated ways just to have more 'features'. Nowdays the web only wants to add realtime in any sentence and thanks to HTML5 and Websockets it's a pretty easy thing to do but... doing that with ruby gets overcomplicated.

Trying to find a simple solution i've researched a lot. I've found Cramp to work pretty well, but requiring activesupport it's against my religion :D.

After some googling and githubbing i've found websocket-rack which is a clean and simple solution for a problem that it's actually simple.

 1 require 'cuba'
 2 require 'rack/websocket'
 3 
 4 class Websockets < Rack::WebSocket::Application
 5   def on_open(env)
 6     send_data("Welcome")
 7   end
 8 
 9   def on_message(env, message)
10     send_data(message.reverse)
11   end
12 end
13 
14 Cuba.define do
15   on "ws" { run Websockets.new }
16 
17   on "" do
18     res.write "The websockets are in /ws"
19   end
20 end

This is a silly example, but enough in most of the cases, in here you will have to choose a way to id the clients and send them some messages but that's the fun part.