Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Track message history up to 50 messages

  • Loading branch information...
commit d05ab736c2ae5d16ff48aea82f26a478b0634ffb 1 parent 80126d8
@tarcieri authored
View
7 app/actions/history_action.rb
@@ -0,0 +1,7 @@
+class HistoryAction < Cramp::Action
+ def start
+ history = {:history => ChatServer.actor.history}.to_json
+ render history
+ finish
+ end
+end
View
17 app/models/chat_server.rb
@@ -2,6 +2,7 @@
class ChatServer
include Celluloid
+ attr_reader :history
def self.start
supervise_as :chat_server
@@ -13,26 +14,40 @@ def self.actor
def initialize
@users = {}
+ @history = History.new
end
def register(name, client)
@users[name] = client
+ event :join, name
publish :control, name, 'joined the chat room'
end
def unregister(name)
@users.delete name
+ event :part, name
publish :control, name, 'left the chat room'
end
def send_message(user, str)
+ event :message, user, str
publish :message, user, str
end
-
+
def users
@users.map { |name, _| {:name => name} }
end
+ def event(type, user, str = nil)
+ ev = {
+ :event => type,
+ :ts => Time.now.xmlschema,
+ :user => user
+ }
+ ev.merge!(:text => str) if str
+ @history << ev
+ end
+
def publish(type, user, str)
msg = {:action => type, :user => user, :message => str}.to_json
View
21 app/models/history.rb
@@ -0,0 +1,21 @@
+class History
+ DEFAULT_BACKLOG = 50
+
+ def initialize(backlog = DEFAULT_BACKLOG)
+ @timeline, @backlog = [], DEFAULT_BACKLOG
+ end
+
+ def push(message)
+ @timeline << message
+ @timeline.shift if @timeline.size > @backlog
+ end
+ alias_method :<<, :push
+
+ def to_a
+ @timeline
+ end
+
+ def to_json(opts = nil)
+ @timeline.to_json(opts)
+ end
+end
View
1  config/routes.rb
@@ -2,5 +2,6 @@
HttpRouter.new do
add('/').to(HomeAction)
get('/users').to(UsersAction)
+ get('/history').to(HistoryAction)
get('/websocket').to(ChatClient)
end
Please sign in to comment.
Something went wrong with that request. Please try again.