How can I get the Clojurescript namespace I am in from within a clojurescript program?

别来无恙 提交于 2019-12-07 00:53:56

问题


How can I get the Clojurescript namespace I am in from within a clojurescript program? I want to do this do provide certain debug information (it only needs to work in dev mode)


回答1:


Namespaces are not first class in ClojureScript as they are in Clojure. There's absolutely no way to get the namespace at runtime. It is possible to get this information at macroexpansion time if you're not afraid of accessing some the ClojureScript compiler internals. There should probably be an API for this - but we're not there yet.




回答2:


You can get the name of the current namespace with this trick, which takes advantage of :: creating a namespaced symbol for you in the current namespace:

(namespace ::x)

You probably don't want to use that value for anything, because if the code is compiled the internal representation will change. If you want to live dangerously, then in the browser you can then access the js object that holds the namespace like this:

(reduce (fn [ns n] (aget ns n))
        js/window
        (clojure.string/split (namespace ::x) #"\."))



回答3:


During macro-expansion you can access &env and retrieve namespace information from the :ns key like this:

(:ns &env)
(:name (:ns &env))

This only works at macro-expansion/compile time and not at runtime.




回答4:


You can try this

(apply str (drop-last 2 (str `_)))


来源:https://stackoverflow.com/questions/16656481/how-can-i-get-the-clojurescript-namespace-i-am-in-from-within-a-clojurescript-pr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!