diff --git a/src/dojo/handler.clj b/src/dojo/handler.clj index eeec32d..199df95 100644 --- a/src/dojo/handler.clj +++ b/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 [] diff --git a/test/dojo/handler_test.clj b/test/dojo/handler_test.clj index 7936013..18e85fc 100644 --- a/test/dojo/handler_test.clj +++ b/test/dojo/handler_test.clj @@ -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})))))