Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sinatra Async UI chat
#!/usr/bin/env ruby
# coding: utf-8
require 'sinatra'
set :server, 'thin'
set :sessions, true
streams = Hash.new {|k, v| k[v] = [] }
helpers do
def session_id
session['session_id']
end
end
get '/' do
halt erb(:login) unless params[:user]
erb :chat, :locals => { :user => params[:user].gsub(/\W/, '') }
end
get '/async' do
halt erb(:login) unless params[:user]
erb :chatasync, :locals => { :user => params[:user].gsub(/\W/, '') }
end
get '/stream', :provides => 'text/event-stream' do
stream :keep_open do |out|
streams[session_id] << out
out.callback { streams[session_id].delete(out) }
end
end
post '/' do
streams.each do |id, conns|
# Only send to other clients
next if session_id == id
# Transmit data
conns.each do |out|
out << "data: #{params[:msg]}\n\n"
end
end
204
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> -->
<script src="jquery.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
ul {
list-style: none;
}
</style>
</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
<ul id='chat'></ul>
<script>
var es = new EventSource('/stream');
es.onmessage = function(e) { $('#chat').append($('<li />').text(e.data)); };
$("form").live("submit", function(e) {
var msg = "<%= user %>: " + $('#msg').val();
// Add message once it's received successfully
$.post('/', {msg: msg}).success(function(){
es.onmessage({data: msg});
});
$('#msg').val('');
$('#msg').focus();
e.preventDefault();
});
</script>
<form>
<input id='msg' placeholder='type message here...' />
</form>
<a href="/async?user=<%= user %>">Try asyncronous chat</a>
@@ chatasync
<ul id='chat'></ul>
<script>
var es = new EventSource('/stream');
es.onmessage = function(e) { $('#chat').append($('<li />').text(e.data)); };
// Add message immediately
$("form").live("submit", function(e) {
var msg = "<%= user %>: " + $('#msg').val();
$.post('/', {msg: msg});
es.onmessage({data: msg});
$('#msg').val('');
$('#msg').focus();
e.preventDefault();
});
</script>
<form>
<input id='msg' placeholder='type message here...' />
</form>
<a href="/?user=<%= user %>">Try syncronous chat</a>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment