Skip to content

Commit 3049ce2

Browse files
dynj: add with-bindings
I've written `(with-bindings* m (fn [x] (do-something))` often enough now to wish for a little more convenience.
1 parent 15d6425 commit 3049ce2

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

src/active/clojure/dynj.clj

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,8 @@
3939
"
4040
(:refer-clojure :rename {bound-fn* clj-bound-fn*
4141
binding clj-binding
42-
with-bindings* clj-with-bindings*}))
42+
with-bindings* clj-with-bindings*
43+
with-bindings clj-with-bindings}))
4344

4445
(defn- dynj-name [dynj]
4546
#_(symbol (name (ns-name (:ns (meta dynj))))
@@ -105,6 +106,11 @@
105106
(assert (every? dynj-var? (keys binding-map)))
106107
(clj-with-bindings* binding-map thunk))
107108

109+
(defmacro with-bindings
110+
"Executes `body` using implementations defined via a map of dynj vars."
111+
[binding-map & body]
112+
`(with-bindings* ~binding-map (fn [] ~@body)))
113+
108114
(defn merge-dynjs
109115
"Like merge, but asserts that all keys are dynj vars, and the same
110116
vars are not bound to different implementations."

test/active/clojure/dynj_test.clj

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,13 @@
4545
;; expects a thunk
4646
(fn [] (foo 3))))))
4747

48+
(t/deftest with-bindings-test
49+
(t/is
50+
(= 11
51+
(dynj/with-bindings
52+
{#'foo (fn [x] (+ x 4))}
53+
(foo 7)))))
54+
4855
(dynj/defn-dynj bar [arg]
4956
(* 3 arg))
5057

@@ -56,9 +63,8 @@
5663
b2 {#'bar (fn [x] (str x "foo"))}
5764
bindings (dynj/merge-dynjs b1 b2)]
5865
(t/is "17foo"
59-
(dynj/with-bindings* bindings
60-
(fn []
61-
(bar (foo 16)))))
66+
(dynj/with-bindings bindings
67+
(bar (foo 16))))
6268
(dynj/merge-dynjs b1 b2))
6369
(t/is
6470
(thrown? AssertionError

0 commit comments

Comments
 (0)