Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load-string to current namespace (not core)?

I can load arbitrary Clojure source using:

(load-string source)

However, if namespace wasn't provided, it loads code to clojure.core namespace.

For example, following code:

(load-string "(defn add [a b] (+ a b))")

defines a function:

#'clojure.core/add

Now, is there a way to load that code to some other namespace, preferably the same one in which load-string function is called?

(Other than prepending a namespace declaration to source string before evaluation. I know that it would solve the problem - I'd like to know is there a preferred way)

like image 212
Goran Jovic Avatar asked Jun 22 '11 16:06

Goran Jovic


1 Answers

when def needs to decide what namspace a new function should go in it looks at the the current value of the ns var and adds the new function to that namespace. because ns is a var you can dynamically bind it before you call load-string

user> (binding [*ns* (find-ns 'foo)] (load-string "(defn f [] 4)"))
#'foo/f
user> (foo/f)
4
like image 170
Arthur Ulfeldt Avatar answered Sep 28 '22 09:09

Arthur Ulfeldt