ts3s2g
Last Updated: February 25, 2016
·
1.095K
· blazeeboy

Creating simple network chat using ruby

this is one of the basic scripts i tried to do with every language, and this was never as easy as ruby :) try it in C or C++ and you will have about 100-200 LOC :D

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

1 Response
Add your response

13170

hm... smells bad
- Sinatra has inline templates http://www.sinatrarb.com/intro.html#Inline%20Templates and it's really better
- Why you using ajax when Sinatra can streaming and server events, here is my old code https://github.com/mpakus/simplestreamchat
- for constructions like this last = "<span data-last=\"#{chat.size}\"></span>" it's better to use last = %Q{ ..... #{chat.size} }

over 1 year ago ·