annotate src/clojure/contrib/with_ns.clj @ 10:ef7dbbd6452c

added clojure source goodness
author Robert McIntyre <rlm@mit.edu>
date Sat, 21 Aug 2010 06:25:44 -0400
parents
children
rev   line source
rlm@10 1 ;;; with_ns.clj -- temporary namespace macro
rlm@10 2
rlm@10 3 ;; by Stuart Sierra, http://stuartsierra.com/
rlm@10 4 ;; March 28, 2009
rlm@10 5
rlm@10 6 ;; Copyright (c) Stuart Sierra, 2009. All rights reserved. The use
rlm@10 7 ;; and distribution terms for this software are covered by the Eclipse
rlm@10 8 ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
rlm@10 9 ;; which can be found in the file epl-v10.html at the root of this
rlm@10 10 ;; distribution. By using this software in any fashion, you are
rlm@10 11 ;; agreeing to be bound by the terms of this license. You must not
rlm@10 12 ;; remove this notice, or any other, from this software.
rlm@10 13
rlm@10 14
rlm@10 15 (ns
rlm@10 16 ^{:author "Stuart Sierra",
rlm@10 17 :doc "Temporary namespace macro"}
rlm@10 18 clojure.contrib.with-ns)
rlm@10 19
rlm@10 20 (defmacro with-ns
rlm@10 21 "Evaluates body in another namespace. ns is either a namespace
rlm@10 22 object or a symbol. This makes it possible to define functions in
rlm@10 23 namespaces other than the current one."
rlm@10 24 [ns & body]
rlm@10 25 `(binding [*ns* (the-ns ~ns)]
rlm@10 26 ~@(map (fn [form] `(eval '~form)) body)))
rlm@10 27
rlm@10 28 (defmacro with-temp-ns
rlm@10 29 "Evaluates body in an anonymous namespace, which is then immediately
rlm@10 30 removed. The temporary namespace will 'refer' clojure.core."
rlm@10 31 [& body]
rlm@10 32 `(try
rlm@10 33 (create-ns 'sym#)
rlm@10 34 (let [result# (with-ns 'sym#
rlm@10 35 (clojure.core/refer-clojure)
rlm@10 36 ~@body)]
rlm@10 37 result#)
rlm@10 38 (finally (remove-ns 'sym#))))