Un Chat con Ajax y JQuery

Donde

chat.rb

[~/sinatra/sinatra-streaming/blazeeboychat(master)]$ cat chat.rb
require 'sinatra' 
require 'sinatra/reloader' if development?
#set :port, 3000
#set :environment, :production

chat = ['welcome..']

get('/') { erb :index }

get '/send' do
  return [404, {}, "Not an ajax request"] unless request.xhr?
  chat << "#{request.ip} : #{params['text']}"
  nil
end

get '/update' do
  return [404, {}, "Not an ajax request"] unless request.xhr?
  @updates = chat[params['last'].to_i..-1] || []

  @last = chat.size
  erb <<-'HTML', :layout => false
      <% @updates.each do |phrase| %>
        <%= phrase %> <br />
      <% end %>
      <span data-last="<%= @last %>"></span>
  HTML
end

views/index.erb

[~/sinatra/sinatra-streaming/blazeeboychat(master)]$ cat views/layout.erb 
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="simple.css">
  </head>
  <body>
    <%= yield %>

    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script src= "chat.js"></script>
  </body>
</html>

[~/sinatra/sinatra-streaming/blazeeboychat(master)]$ cat views/index.erb 
<input id="text" placeholder="Write then press Enter." autofocus />
<div id="chat"></div>

chat.js

[~/sinatra/sinatra-streaming/blazeeboychat(master)]$ cat public/chat.js 
$('#text').keypress(
  function(e){
    if( e.keyCode==13 ){
      $.get('/send',{text:$('#text').val()});
      $('#text').val('');
    } 
  }
);

(function() {
  var last = 0;
  setInterval(
    function(){
      $.get('/update',{last: last},
        function(response){
          last = $('<p>').html(response).find('span').data('last');
          $('#chat').append(response);
        }
      );
    },
  1000);
})();

El método get de jQuery

jQuery.get( url [, data ] [, success ] [, dataType ] )  Returns: jqXHR

This is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});
The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response.

It is also passed the text status of the response.

Rakefile

[~/sinatra/sinatra-streaming/blazeeboychat(master)]$ cat Rakefile 
task :default => :server

desc "run the chat server"
task :server do
  sh "bundle exec ruby chat.rb"
end

desc "make a non Ajax request via curl"
task :noajax do
  sh "curl -v http://localhost:4567/update"
end

desc "make an Ajax request via curl"
task :ajax do
  sh %q{curl -v -H "X-Requested-With: XMLHttpRequest" localhost:4567/update}
end

desc "Visit the GitHub repo page"
task :open do
  sh "open https://github.com/crguezl/chat-blazee"
end

Gemfile

~/sinatra/sinatra-streaming/blazeeboychat(master)]$ cat Gemfile
source 'https://rubygems.org'

gem 'thin'

group :development do
  gem 'sinatra-contrib'
end

public/simple.css

[~/sinatra/sinatra-streaming/blazeeboychat(master)]$ cat public/simple.css 
#text {width:100%; font-size: 15px; padding: 5px; display: block;}



Subsecciones
Casiano Rodriguez León 2015-01-07