Skip to content

Instantly share code, notes, and snippets.

@bjering
Created August 23, 2010 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjering/fd6b3bf4d2426b95aed0 to your computer and use it in GitHub Desktop.
Save bjering/fd6b3bf4d2426b95aed0 to your computer and use it in GitHub Desktop.
(ns chat.channel
(:use
[clojure.contrib.def]
[chat.common]))
(defvar channels (agent {}))
(defn- list-users
[channel]
(map #(% :user-name) (@channel :users)))
(defn- write
[channel message]
(doseq [user (@channel :users)]
(user :send :write message))
nil)
(defn- say
[channel user-name message]
(write channel (str "message " (@channel :channel-name) " " user-name " " message)))
(defn- user-join
[channel user-name]
(write channel (str "join " (@channel :channel-name) " " user-name)))
(defn- leave
[channel user-name]
(write channel (str "leave " (@channel :channel-name) " " user-name)))
(defn dispatcher
[state message & args]
(cond
(= message :agent) state
(= message :state) @state
(= message :channel-name) (@state :channel-name)
(= message :list-users) (apply list-users state args)
(= message :join) (apply user-join state args)
(= message :leave) (apply leave state args)
(= message :say) (apply say state args)
(= message :send)
(do
(apply chat.common/send-message state args)
(partial dispatcher state))
:else (throw (IllegalArgumentException.
(str "unknown message in [" "channel" "] " message)))))
(defn- add-user
[channel user]
(conj channel {:users (conj (channel :users) user)}))
(defn create
[channel-name]
(let
[
new-channel
(partial dispatcher
(agent
{
:channel-name channel-name
:users '()
:add-user add-user
}))]
(send channels conj {channel-name new-channel})
new-channel))
(defn delete-all
[]
(defvar channels (agent {})))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment