diff 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
line wrap: on
line diff
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/clojure/contrib/with_ns.clj	Sat Aug 21 06:25:44 2010 -0400
     1.3 @@ -0,0 +1,38 @@
     1.4 +;;; with_ns.clj -- temporary namespace macro
     1.5 +
     1.6 +;; by Stuart Sierra, http://stuartsierra.com/
     1.7 +;; March 28, 2009
     1.8 +
     1.9 +;; Copyright (c) Stuart Sierra, 2009. All rights reserved.  The use
    1.10 +;; and distribution terms for this software are covered by the Eclipse
    1.11 +;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
    1.12 +;; which can be found in the file epl-v10.html at the root of this
    1.13 +;; distribution.  By using this software in any fashion, you are
    1.14 +;; agreeing to be bound by the terms of this license.  You must not
    1.15 +;; remove this notice, or any other, from this software.
    1.16 +
    1.17 +
    1.18 +(ns 
    1.19 +  ^{:author "Stuart Sierra",
    1.20 +     :doc "Temporary namespace macro"}
    1.21 +  clojure.contrib.with-ns)
    1.22 +
    1.23 +(defmacro with-ns
    1.24 +  "Evaluates body in another namespace.  ns is either a namespace
    1.25 +  object or a symbol.  This makes it possible to define functions in
    1.26 +  namespaces other than the current one."
    1.27 +  [ns & body]
    1.28 +  `(binding [*ns* (the-ns ~ns)]
    1.29 +     ~@(map (fn [form] `(eval '~form)) body)))
    1.30 +
    1.31 +(defmacro with-temp-ns
    1.32 +  "Evaluates body in an anonymous namespace, which is then immediately
    1.33 +  removed.  The temporary namespace will 'refer' clojure.core."
    1.34 +  [& body]
    1.35 +  `(try
    1.36 +    (create-ns 'sym#)
    1.37 +    (let [result# (with-ns 'sym#
    1.38 +                    (clojure.core/refer-clojure)
    1.39 +                    ~@body)]
    1.40 +      result#)
    1.41 +    (finally (remove-ns 'sym#))))