November 30, 2014

Stumbling on Clojure I - Resource Files


We need to externalize some configuration variables; e.g. database basic settings like port, host, etc.

When using lein, we can put the configuration file under the resources directory and store it as a clojure file (a .clj extension). In this example, we will store the settings as a map.

;file name: settings.clj
{:setting1 "Setting 1" :setting2 "Setting 2"}

We can then read this file and parse the entry as a map.

(require '[clojure.edn :as edn]
		 '[ :as io])

	"settings.clj" io/resource slurp edn/read-string)

This will output the map

{:setting1 "Setting 1" :setting2 "Setting 2"}

We can write a function that reads the map from a file:

(defn read-settings [file-name] 

So now we can read any resource file:

(read-settings "file1.clj")

Or we can set a global variable with the predefined setings:

(def app-settings (read-settings "settings.clj"))

And access that variable like a map:

(:setting1 app-settings)
=> "Setting 1"
Tags: clojure edn resource files