Permalink
Browse files

Fixed variable capture

  • Loading branch information...
1 parent c05e663 commit 46148ef439c02cf1f78b702ee5b31725ce30b462 Andrey Paramonov committed Nov 25, 2012
Showing with 13 additions and 4 deletions.
  1. +5 −4 src/dojo/handler.clj
  2. +8 −0 test/dojo/handler_test.clj
View
@@ -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 []
@@ -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.