Skip to content

Instantly share code, notes, and snippets.

@RutledgePaulV
Created October 31, 2018 19:41
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 RutledgePaulV/6b91519cb71cd659e85bb3d091f9a31d to your computer and use it in GitHub Desktop.
Save RutledgePaulV/6b91519cb71cd659e85bb3d091f9a31d to your computer and use it in GitHub Desktop.
Like with-redefs but local to the thread. Doesn't require dynamic function vars.
(def ^:dynamic *hook* false)
(defn hook [var f]
(alter-var-root var
(fn [original]
(fn [& args]
(if *hook*
(apply f args)
(apply original args))))))
(defmacro with-redefs*
"Like with-redefs but scoped to only the
thread of execution."
[bindings & body]
`(let [m# ~(zipmap (take-nth 2 bindings)
(take-nth 2 (next bindings)))]
(doseq [[k# v#] m#] (hook k# v#))
(binding [*hook* true] ~@body)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment