Sha256: 61cf88460f650bccf0d8082d7d9252d39d8e5c7bd5f4cd3e8eac65960073a8c2

Contents?: true

Size: 1.33 KB

Versions: 10

Compression:

Stored size: 1.33 KB

Contents

#!/usr/bin/env ruby -I ../lib -I lib
# frozen_string_literal: true

require_relative 'rainbows'

require 'sinatra'
set :server, :rainbows
connections = []

get '/' do
  halt erb(:login) unless params[:user]
  erb :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" }
  204 # response without entity body
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>
  </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
<pre id='chat'></pre>
<form>
  <input id='msg' placeholder='type message here...' />
</form>

<script>
  // reading
  var es = new EventSource('/stream');
  es.onmessage = function(e) { $('#chat').append(e.data + "\n") };

  // writing
  $("form").on('submit',function(e) {
    $.post('/', {msg: "<%= user %>: " + $('#msg').val()});
    $('#msg').val(''); $('#msg').focus();
    e.preventDefault();
  });
</script>

Version data entries

10 entries across 10 versions & 2 rubygems

Version Path
rubypitaya-3.12.5 ./lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/sinatra-3.0.5/examples/chat.rb
rubypitaya-3.12.4 ./lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/sinatra-3.0.5/examples/chat.rb
rubypitaya-3.12.3 ./lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/sinatra-3.0.5/examples/chat.rb
rubypitaya-3.12.2 ./lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/sinatra-3.0.5/examples/chat.rb
sinatra-3.0.5 examples/chat.rb
sinatra-3.0.4 examples/chat.rb
sinatra-3.0.3 examples/chat.rb
sinatra-3.0.2 examples/chat.rb
sinatra-3.0.1 examples/chat.rb
sinatra-3.0.0 examples/chat.rb