Created
April 29, 2012 15:37
-
-
Save mamantoha/2551354 to your computer and use it in GitHub Desktop.
Simple Chat with Sinatra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- encoding: utf-8 -*- | |
require 'sinatra' | |
require 'slim' | |
set :server, 'thin' | |
connections = [] | |
get '/' do | |
halt slim(:login) unless params[:user] | |
slim :chat, :locals => { :user => params[:user].gsub(/\W/, '') } | |
end | |
get '/stream', :provides => 'text/event-stream' do | |
stream :keep_open do |out| | |
connections << out | |
out.callback { connections.delete(out) } | |
end | |
end | |
post '/' do | |
connections.each { |out| out << "data: #{params[:msg]}\n\n" } | |
# http://ru.wikipedia.org/wiki/Список_кодов_состояния_HTTP#204 | |
204 # response without entity body | |
end | |
__END__ | |
@@ layout | |
html | |
head | |
title Simple Chat with Sinatra | |
meta charset="utf-8" | |
script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" | |
body | |
== yield | |
@@ login | |
form action='/' | |
label for='user' User Name: | |
input name='user' value='' | |
input type='submit' value="GO!" | |
@@ chat | |
form | |
input id='msg' placeholder='type message here...' | |
pre id='chat' | |
javascript: | |
// 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(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment