clojure - 我想在 clojure 的沙盒命名空间中运行加载文件

标签 clojure namespaces

我是 Clojure 新手,为了乐趣/教育,我正在为 lein 编写一个通用迁移框架。该系统必须做的一件事是从磁盘读取 clojure 文件,然后运行 ​​up 函数或 down 函数。我认为这个文件可能应该在临时命名空间中进行评估,但我很难让它工作。这是我到目前为止所拥有的:

(def user-namespace (create-ns 'leiningen.generic-migrate.user-eval))

(defn load-migration-file [file]
  (binding [*ns* user-namespace]
    (load-file (.getAbsolutePath file))
    (keys (ns-publics *ns*))))

这给了我错误:

Unable to resolve symbol: defn in this context

我的问题是,使用加载文件然后运行定义的函数的最佳方法是什么,而不会有有人覆盖我的命名空间中的内容的风险?

最佳答案

(defmacro with-ns
  "Evaluates body in another namespace.  ns is either a namespace
  object or a symbol.  This makes it possible to define functions in
  namespaces other than the current one."
  [ns & body]
  `(binding [*ns* (the-ns ~ns)]
     ~@(map (fn [form] `(eval '~form)) body)))

(defmacro with-temp-ns
  "Evaluates body in an anonymous namespace, which is then immediately
  removed.  The temporary namespace will 'refer' clojure.core."
  [& body]
  `(try
     (create-ns 'sym#)
     (let [result# (with-ns 'sym#
                     (clojure.core/refer-clojure)
                     ~@body)]
       result#)
     (finally (remove-ns 'sym#))))

关于clojure - 我想在 clojure 的沙盒命名空间中运行加载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27343707/

相关文章:

xml - 创建没有域的 XML 命名空间

c++ - 类继承后不可访问

.net - System.Web.Mvc 与 Microsoft.Web.Mvc

clojure - 为了 Clojure(性能),我应该使用哪个版本的 Java?

clojure - 仅在原子值更改时调用副作用函数

java - 在 Java 接口(interface)上调用 .class 时将 .class 传递给 Clojure 函数

zend-framework - 如何在zend框架中注册自定义库

clojure - 如何在 map 内创建 map ?

java - 使用 writer 在 Clojure 中编写 CSV 文件

命名空间中允许使用 PHP 保留关键字? (公共(public),私有(private),默认)