public
Created — forked from rkh/chat.rb

Simple Chat Application using the Sinatra Streaming API

  • Download Gist
chat.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
# coding: utf-8
require 'sinatra'
set server: 'thin', connections: []
 
get '/' do
halt erb(:login) unless params[:user]
erb :chat, locals: { user: params[:user].gsub(/\W/, '') }
end
 
get '/stream', provides: 'text/event-stream' do
stream :keep_open do |out|
settings.connections << out
out.callback { settings.connections.delete(out) }
end
end
 
post '/' do
settings.connections.each { |out| out << "data: #{params[:msg]}\n\n" }
204 # response without entity body
end
 
__END__
 
@@ layout
<html>
<head>
<title>Super Simple Chat with Sinatra</title>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
</head>
<body><%= yield %></body>
</html>
 
@@ login
<form action='/'>
<label for='user'>User Name:</label>
<input name='user' value='' />
<input type='submit' value="GO!" />
</form>
 
@@ chat
<pre id='chat'></pre>
 
<script>
// reading
var es = new EventSource('/stream');
es.onmessage = function(e) { $('#chat').append(e.data + "\n") };
 
// writing
$("form").live("submit", function(e) {
$.post('/', {msg: "<%= user %>: " + $('#msg').val()});
$('#msg').val(''); $('#msg').focus();
e.preventDefault();
});
</script>
 
<form>
<input id='msg' placeholder='type message here...' />
</form>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.