Permalink
Browse files

initial commit

  • Loading branch information...
0 parents commit 667d2a171731d26ba143858249fd81c97221da3e @akitaonrails akitaonrails committed Jan 12, 2010
No changes.
@@ -0,0 +1,7 @@
+class ApplicationController < Cramp::Controller::Action
+ include ApplicationHelper
+end
+
+class WebSocketApplicationController < Cramp::Controller::Websocket
+ include ApplicationHelper
+end
@@ -0,0 +1,28 @@
+class ChatController < WebSocketApplicationController
+ periodic_timer :retrieve_messages, :every => 2
+ on_data :receive_message
+
+ def retrieve_messages
+ @last_message ||= (Time.now - 1.minute)
+ Chat.recent(@last_message).all do |messages|
+ messages.each { |msg| render( formatted_msg(msg) ) }
+ @last_message = messages.first.try(:sent_at) || @last_message
+ end
+ end
+
+ def receive_message(data)
+ params = Rack::Utils.parse_query(data)
+
+ chat = Chat.new :name => params["from"],
+ :sent_at => Time.now,
+ :message => params["msg"]
+
+ chat.save do |status|
+ if status.success?
+ render formatted_msg("Message Successfully Received.")
+ else
+ render formatted_msg("Error receiving message: #{status.inspect}.")
+ end
+ end
+ end
+end
@@ -0,0 +1,24 @@
+class ReceiveController < ApplicationController
+ before_start :prepare_params
+ on_start :receive_message
+
+ def prepare_params
+ @params = request.params
+ yield
+ end
+
+ def receive_message
+ chat = Chat.new :name => @params["from"],
+ :sent_at => Time.now,
+ :message => @params["msg"]
+
+ chat.save do |status|
+ if status.success?
+ render formatted_msg("Message Successfully Received.")
+ else
+ render formatted_msg("Error receiving message: #{status.inspect}.")
+ end
+ finish
+ end
+ end
+end
@@ -0,0 +1,13 @@
+class RetrieveController < ApplicationController
+ on_start :retrieve_messages
+
+ def retrieve_messages
+ @last_message ||= (Time.now - 30.seconds)
+ Chat.recent(@last_message).all do |messages|
+ messages.each { |msg| render( formatted_msg(msg) ) }
+ @last_message = messages.first.try(:sent_at) || @last_message
+ finish
+ end
+ end
+
+end
@@ -0,0 +1,13 @@
+module ApplicationHelper
+ private
+ def formatted_msg(message)
+ if message.is_a? Chat
+ ["<div>
+ <span class=\"from\">At #{message.sent_at.to_formatted_s(:short)}, #{message.name} said:</span>
+ <span class=\"msg\">#{message.message}</span>
+ </div>", "\n"]
+ else
+ ["<p>#{message}</p>", "\n"]
+ end
+ end
+end
@@ -0,0 +1,21 @@
+class Chat < Cramp::Model::Base
+ attribute :id, :type => Integer, :primary_key => true
+ attribute :name
+ attribute :sent_at
+ attribute :message
+
+ def sent_at
+ Time.parse(read_attribute(:sent_at))
+ end
+
+ def sent_at=(value)
+ write_attribute(:sent_at, value.to_formatted_s(:db))
+ end
+
+ def self.recent(last_message)
+ where(Chat[:sent_at].gt(last_message.to_formatted_s(:db))).
+ order(Chat[:sent_at].asc)
+ end
+
+ validates_presence_of :name
+end
@@ -0,0 +1,23 @@
+require 'rubygems'
+require 'usher'
+require 'thin'
+require 'cramp/controller'
+require 'cramp/model'
+require 'ruby-debug'
+require 'active_support/all'
+
+require 'config/routes'
+require 'app/helpers/application'
+require 'app/controllers/application_controller'
+require 'app/controllers/chat_controller'
+require 'app/controllers/retrieve_controller'
+require 'app/controllers/receive_controller'
+require 'app/models/chat'
+require 'lib/fixes'
+
+require 'rack'
+
+Cramp::Model.init(YAML.load(File.read('./config/database.yml')))
+Cramp::Controller::Websocket.backend = :thin
+Thin::Logging.trace = true
+Rack::Handler::Thin.run app_routes, :Port => 3000
@@ -0,0 +1,13 @@
+create database cramp_chat_development
+ default character set utf8
+ default collate utf8_general_ci;
+
+use cramp_chat_development;
+
+create table chat (
+ id int not null auto_increment,
+ name varchar(100) not null,
+ message text,
+ sent_at datetime,
+ primary key(id)
+);
@@ -0,0 +1,3 @@
+---
+:database: cramp_chat_development
+:username: root
@@ -0,0 +1,30 @@
+def app_routes
+ Usher::Interface.for(:rack) do
+ get('/').to(ChatController)
+ get('/retrieve').to(RetrieveController)
+ post('/receive').to(ReceiveController)
+ end
+
+ # Rack::Builder.new do
+ # use Rack::Static, :urls => ["/demo"]
+ # use Rack::Session::Cookie
+ #
+ # routes = Usher::Interface.for(:rack) do
+ # get('/').to(ChatController)
+ # get('/retrieve').to(RetrieveController)
+ # post('/receive').to(ReceiveController)
+ # end
+ # run routes
+ # end
+
+ # Rack::Builder.new do
+ # use Rack::ContentType, "text/html"
+ # use Rack::Static, :urls => ["/demo"]
+ # use Rack::Session::Cookie
+ #
+ # map("/") { run RetrieveController }
+ # map("/retrieve") { run RetrieveController }
+ # map("/receive") { run ReceiveController }
+ # end
+
+end
@@ -0,0 +1,10 @@
+require 'rubygems'
+require 'sinatra'
+require 'thin'
+
+class MyApp < Sinatra::Base
+ enable :static
+end
+
+Thin::Logging.trace = true
+Rack::Handler::Thin.run MyApp, :Port => 3001
@@ -0,0 +1,15 @@
+# monkey patch for activerecord dependency in Cramp::Model
+module Cramp
+ module Model
+ module Quoting
+ def quoted_date(value)
+ if value.acts_like?(:time)
+ zone_conversion_method = :getutc # modified line
+ value.respond_to?(zone_conversion_method) ? value.send(zone_conversion_method) : value
+ else
+ value
+ end.to_s(:db)
+ end
+ end
+ end
+end
@@ -0,0 +1,84 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<!-- Copyright (c) 2008 Dustin Sallings <dustin+html@spy.net> -->
+<html lang="en">
+ <head>
+ <title>chat</title>
+ <style type="text/css" media="screen">
+ #messages {
+ width: 400px;
+ height: 250px;
+ overflow: auto;
+ }
+ </style>
+ </head>
+
+ <body>
+ <h1>Welcome to Chat</h1>
+
+ <div id="messages">
+ <div>
+ <span class="from">First!:</span>
+ <span class="msg">Welcome to chat. Please don't hurt each other.</span>
+ </div>
+ </div>
+
+ <form id="chat-form" onsubmit="onSubmit(); return false;">
+ <div><label for="from">Nick:</label> <input id='from' type="text" name="from" value="Foo"/></div>
+ <div><label for="msg">Message:</label></div>
+ <div><textarea id='msg' name="msg" rows="3" cols="50"></textarea></div>
+ <div><input type="submit" value="Say it" id="submit"/></div>
+ </form>
+
+ <script type="text/javascript"
+ src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
+ <script type="text/javascript" src="javascript/swfobject.js"></script>
+ <script type="text/javascript" src="javascript/FABridge.js"></script>
+ <script type="text/javascript" src="javascript/web_socket.js"></script>
+ <script type="text/javascript">
+
+ // Set URL of your WebSocketMain.swf here:
+ WebSocket.__swfLocation = "javascript/WebSocketMain.swf";
+
+ var ws;
+
+ function initConnection() {
+ // Connect to Web Socket.
+ // Change host/port here to your own Web Socket server.
+ ws = new WebSocket("ws://foo.com.br:3000/");
+
+ // Set event handlers.
+ ws.onopen = function() {
+ output("<p>Connection opened</p>");
+ };
+ ws.onmessage = function(e) {
+ // e.data contains received string.
+ output(e.data);
+ };
+ ws.onclose = function() {
+ output("<p>Connection closed</p>");
+ initConnection(); // reconnect
+ };
+ }
+
+ $(document).ready(function() {
+ initConnection();
+ $("#msg").focus();
+ });
+
+ function onSubmit() {
+ ws.send($("#chat-form").serialize());
+ $("#msg").val("");
+ $("#msg").focus();
+ }
+
+ function output(str) {
+ $("#messages").append(str);
+ var messages = document.getElementById("messages");
+ messages.scrollTop = messages.scrollHeight;
+ }
+
+ </script>
+ </body>
+</html>
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<!-- Copyright (c) 2008 Dustin Sallings <dustin+html@spy.net> -->
+<html lang="en">
+ <head>
+ <title>chat</title>
+ <style type="text/css" media="screen">
+ #messages {
+ width: 400px;
+ height: 250px;
+ overflow: auto;
+ }
+ </style>
+ </head>
+
+ <body>
+ <h1>Welcome to Chat</h1>
+
+ <div id="messages">
+ <div>
+ <span class="from">First!:</span>
+ <span class="msg">Welcome to chat. Please don't hurt each other.</span>
+ </div>
+ </div>
+
+ <form id="chat-form" onsubmit="onSubmit(); return false;">
+ <div><label for="from">Nick:</label> <input id='from' type="text" name="from" value="Foo"/></div>
+ <div><label for="msg">Message:</label></div>
+ <div><textarea id='msg' name="msg" rows="3" cols="50"></textarea></div>
+ <div><input type="submit" value="Say it" id="submit"/></div>
+ </form>
+
+ <script type="text/javascript"
+ src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
+ <script type="text/javascript">
+ // method used to update element html
+ $(document).ready(function() {
+ $("#msg").focus();
+ setInterval(function() {
+ $.ajax({
+ url: "http://foo.com.br:3000/retrieve",
+ type: "GET",
+ success: output,
+ })
+ }, 3000);
+ });
+
+ function onSubmit() {
+ $.ajax({
+ url: "http://foo.com.br:3000/receive",
+ type: "GET",
+ data: $("#chat-form").serialize(),
+ success: output,
+ });
+ $("#msg").val("").focus();
+ }
+
+ function output(str) {
+ $("#messages").append(str);
+ var messages = document.getElementById("messages");
+ messages.scrollTop = messages.scrollHeight;
+ }
+
+ </script>
+ </body>
+</html>
Oops, something went wrong.

0 comments on commit 667d2a1

Please sign in to comment.