Skip to content

Instantly share code, notes, and snippets.

@philoskim
Last active May 4, 2018 08:49
Show Gist options
  • Save philoskim/19bafdac0d9d5610408157e528c053d6 to your computer and use it in GitHub Desktop.
Save philoskim/19bafdac0d9d5610408157e528c053d6 to your computer and use it in GitHub Desktop.
How to get *ns* string in ClojureScript

How to get *ns* string in ClojureScript

It’s not so easy to get *ns* string in ClojureScript as you might expect but here is a tip.

It is impossible to get *ns* string at run-time in ClojureScript (except in self-hosted ClojureScript) but it can be accessed at compile-time only. So you have to use a macro to get it as the following example.

I came up with this idea in the course of implementing set-ns-blacklist! and set-ns-whitelist! (https://github.com/philoskim/debux#debux-config) in my debux library.

example/macro.clj
(ns example.macro)

(defmacro current-ns []
  (str *ns*))
example/lab.cljs
(ns example.lab
  (:require-macros [example.macro :refer [current-ns]]))

(current-ns)
; => "example.lab"
@Menthalion
Copy link

Menthalion commented Apr 9, 2018

What about (str (.getName *ns*))?

@philoskim
Copy link
Author

philoskim commented Apr 10, 2018

@Menthalion

The followings have the same result.

(str *ns*)

(str (.getName *ns*))

(str (ns-name *ns*))

Both (.getName *ns*) and (ns-name *ns*) return the clojure.lang.Symbol type.

Do you have any opinion or reason about which one is better?

See here (http://cljs.github.io/api/cljs.core/STARnsSTAR) for one example.

Anyway thanks for suggestion!

@didibus
Copy link

didibus commented May 4, 2018

Cool macro.

I also realized you can use ::. So something like:

(->> (clojure.string/split ::test #"/") first (drop 1) (clojure.string/join))

Also works, and does not require the use of a macro.

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