Skip to content

Commit

Permalink
Fixed variable capture
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrey Paramonov committed Nov 25, 2012
1 parent c05e663 commit 46148ef
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/dojo/handler.clj
@@ -1,10 +1,11 @@
(ns dojo.handler)

(defmacro handler [name args & body]
`(fn [~'msg]
(let [~@(mapcat (fn [x] [x `(get ~'msg ~(keyword x))]) args)]
(when (or ~@args)
~@body))))
(let [msg (gensym)]
`(fn [~msg]
(let [~@(mapcat (fn [x] [x `(get ~msg ~(keyword x))]) args)]
(when (or ~@args)
~@body)))))

(defmacro build-handlers [& body]
`(defn- handlers []
Expand Down
8 changes: 8 additions & 0 deletions test/dojo/handler_test.clj
Expand Up @@ -8,3 +8,11 @@
(is (= ["Document:A:null" "Note:B:null" "Alert:A:B"] (on-message {:id 1 :a "A" :b "B"})))
(is (= ["Document:A:C" "Note:null:C" "Alert:A:null"] (on-message {:id 2 :a "A" :c "C"})))
(is (= ["Document:A:C" "Note:B:C" "Alert:A:B"] (on-message {:id 2 :a "A" :b "B" :c "C"}))))

(deftest var-capturing-test
(let [msg-handler (handler msg [msg something]
(format "Msg:%s:%s" msg something))
x-handler (handler x [x something]
(format "X:%s:%s" x something))]
(is (= "Msg:3:5" (msg-handler {:msg 3 :something 5})))
(is (= "X:3:5" (x-handler {:x 3 :something 5})))))

0 comments on commit 46148ef

Please sign in to comment.