Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure - eval code in different namespace

I'm coding something like REPL Server. Request from users evaluates in such function:

(defn execute [request]
  (str (try
          (eval (read-string request))
        (catch Exception e (.getLocalizedMessage e)))))

Each client in separate thread. But they have the same namespace. How can I run code in dynamic created namespace ? So when new client connected, I want to create new namespace and to run client handling loop code there. Or maybe it's possible to run (eval ..) in other namespace ?

Thanks.

upd.
Solved!

Execute function:

(defn execute  
  "evaluates s-forms"  
  ([request] (execute request *ns*))  
  ([request user-ns]  
    (str  
      (try  
        (binding [*ns* user-ns] (eval (read-string request)))  
        (catch Exception e (.getLocalizedMessage e))))))

Each client gets it's own namespace by:

(defn generate-ns  
  "generates ns for client connection"  
  [] (let [user-ns (create-ns (symbol (str "client-" (Math/abs (.nextInt random)))))]  
    (execute (str "(clojure.core/refer 'clojure.core)") user-ns)  
    user-ns))`  

(defn delete-ns  
  "deletes ns after client disconnected"  
  [user-ns] (remove-ns (symbol (ns-name user-ns))))

offtop: How to make offsets in code snippets on begin of line ?

like image 598
Andrew Kondratovich Avatar asked Oct 07 '11 08:10

Andrew Kondratovich


2 Answers

Solved:

(binding [*ns* user-ns] (eval (read-string request)))
like image 162
Andrew Kondratovich Avatar answered Oct 18 '22 22:10

Andrew Kondratovich


(symbol (str "client-" (Math/abs (.nextInt random)))

I just wanted to add, that this could be achieved with

(gensym "client-")

(I wanted to comment, but it turns our that I can't :))

like image 30
BillyIII Avatar answered Oct 18 '22 20:10

BillyIII