How do you load program resources such as icons, strings, graphical elements, scripts, and so on in a Clojure program? I am using a project layout similar to that in many Java p
It's the directory structure.
Continuing with the scripting engine example in the OP, a Clojure equivalent would be:
(ns com.domain.example
(:gen-class)
(:import (java.io InputStreamReader))
(:import (javax.script ScriptEngineManager ScriptEngine)))
(defn load-resource
[name]
(let [rsc-name (str "com/domain/resources/" name)
thr (Thread/currentThread)
ldr (.getContextClassLoader thr)]
(.getResourceAsStream ldr rsc-name)))
(defn markdown-to-html
[mkdn]
(let [manager (new ScriptEngineManager)
engine (.getEngineByName manager "js")
is (InputStreamReader. (load-resource "showdown.js"))
_ (.eval engine is)
cnv-arg (str "new Showdown.converter().makeHtml(\"" mkdn "\")")]
(.eval engine cnv-arg)))
(defn -main
[]
(println (markdown-to-html "plain, *emphasis*, **strong**")))
Note that the path to the resources is com/domain/resources
for this code as opposed to com/domain/scriptingtest/resources
in the Java version. In the clojure version, the source file, example.clj
is in com/domain
. In the Java version, the source file, Example.java
is in the com/domain/scriptingtest
package.
When setting up a project in my IDE, NetBeans, the Java project wizard asks for an enclosing package for the source. The Clojure plugin, enclojure, asks for a namespace, not a package. I had never noted that difference before. Hence the "off-by-one" error in the directory structure expected.