我是 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/