Skip to content

Instantly share code, notes, and snippets.

@mjg123
Last active December 11, 2015 00:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjg123/ae4a6e995645c1b64254 to your computer and use it in GitHub Desktop.
Save mjg123/ae4a6e995645c1b64254 to your computer and use it in GitHub Desktop.
(defn ensure-ns [ns-name]
(when-not (find-ns (symbol ns-name))
(.setDynamic
(intern (create-ns (symbol ns-name)) '*me* "never-seen")))
(the-ns (symbol ns-name)))
(defn eval-w-bindings [user-code ns-name user]
(let [my-ns (ensure-ns ns-name)]
(with-bindings {#'*ns* my-ns
(ns-resolve my-ns '*me*) user}
(clojure.core/refer 'clojure.core)
(eval (read-string user-code)))))
(eval-w-bindings "(str \"hello \" *me*)" "mattermost.malory" "andrew")
@mjg123
Copy link
Author

mjg123 commented Dec 11, 2015

That could use some tidying, but behaves as desired:

user=> (eval-w-bindings "(def x 5)" "mattermost.malory" "andrew")
#'mattermost.malory/x
user=> (eval-w-bindings "x" "mattermost.malory" "andrew")
5
user=> (eval-w-bindings "x" "mattermost.drake" "andrew")
CompilerException java.lang.RuntimeException: Unable to resolve symbol: x in this context, compiling:(/private/var/folders/2y/7s5l9gxn3nn6hvvrnllcsw2h0000gn/T/form-init6995876289411288565.clj:1:1)
user=> (eval-w-bindings "mattermost.malory/x" "mattermost.drake" "andrew")
5

@mjg123
Copy link
Author

mjg123 commented Dec 11, 2015

This is a bit of a problem though:

;; good
user=> (eval-w-bindings "(defn x [] *me*)" "ns1" "mjg")
#'ns1/x

;; excellent
user=> (eval-w-bindings "(x)" "ns1" "mjg")
"mjg"

;; oh heck
user=> (eval-w-bindings "(ns1/x)" "ns2" "mjg")
"never-seen"

This happens because it's calling the fn from ns1 but the eval-with-bindings has bound the *me* in ns2. Perhaps the thing to do is to have those vars in the mattermost namespace. In that case the defn above would look like (defn x [] mattermost/*me*), which isn't too bad.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment