Skip to content

Instantly share code, notes, and snippets.

@emad-elsaid
Created March 1, 2014 13:18
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save emad-elsaid/9289678 to your computer and use it in GitHub Desktop.
Save emad-elsaid/9289678 to your computer and use it in GitHub Desktop.
creating simple network chat using ruby
require 'sinatra' # gem install sinatra --no-rdoc --no-ri
set :port, 3000
set :environment, :production
html = <<-EOT
<html><head><style>
#text{width:100%; font-size: 15px; padding: 5px; display: block;}
</style></head><body>
<input id="text" placeholder="Write then press Enter."/>
<div id="chat"></div>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$('#text').keypress(function(e){
if( e.keyCode==13 ){
$.get('/send',{text:$('#text').val()});
$('#text').val('');
}
});
last = 0;
setInterval(function(){
$.get('/update',{last:last},
function(response){
last = $('<p>').html(response).find('span').data('last');
$('#chat').append(response);
});
},1000);
</script>
</body></html>
EOT
chat = ['welcome..']
get('/') { html }
get '/send' do
chat << "#{request.ip} : #{params['text']}"
nil
end
get '/update' do
updates = chat[params['last'].to_i..-1]
last = "<span data-last=\"#{chat.size}\"></span>"
if updates.size>0
updates.join('</br>') + "#{last}</br>"
else
last
end
end
Copy link

ghost commented Mar 17, 2014

This does work, but it will created so muck useless spans.

Some polishing work is needed.

setInterval(function(){
    $.get('/update',{last:last},
        function(response){
            $('#chat').append(response);
            last = $('span[data-last]:last').data('last');
            });
    },1000);
get '/update' do
    updates = chat[params['last'].to_i..-1]
    last = "<span data-last=\"#{chat.size}\"></span>"
    if updates.size>0
        updates.join('</br>') + "#{last}</br>"
    end
end

Anyway, I'm your biggest fan.
:-)

Copy link

ghost commented Mar 17, 2014

sorry, I forgot something

  updates = chat[params['last'].to_i..-1] || chat

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment