2014-12-04 65 views
2

我是新來Clojure和樂趣/教育我正在寫lein的通用遷移框架。該系統需要做的一件事是從磁盤讀取clojure文件,然後運行up函數或down函數。我認爲這個文件應該可以在一個臨時名稱空間中進行評估,但我無法正常工作。這是我到目前爲止有:我想在clojure中的沙盒命名空間中運行加載文件

(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 

我的問題是,什麼是使用負載文件,然後運行一個定義函數的最好的方法,沒有風險有人在我的名字空間覆蓋東西?

回答

3
(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)] 
    [email protected](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) 
        [email protected])] 
     result#) 
    (finally (remove-ns 'sym#))))