【问题标题】:I would like to run load-file in a sandboxed namespace in clojure我想在 clojure 的沙盒命名空间中运行加载文件
【发布时间】:2014-12-04 18:41:50
【问题描述】:

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

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

【问题讨论】:

    标签: clojure namespaces


    【解决方案1】:
    (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#))))
    

    【讨论】:

      猜你喜欢
      • 2021-06-16
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 2020-02-24
      • 2011-08-31
      • 1970-01-01
      • 2012-06-13
      相关资源
      最近更新 更多