Skip to content

Instantly share code, notes, and snippets.

@lygaret
Last active August 29, 2015 14:26
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 lygaret/e49a4a76c3199d811a07 to your computer and use it in GitHub Desktop.
Save lygaret/e49a4a76c3199d811a07 to your computer and use it in GitHub Desktop.
not really useful config loader
(ns my.env
(:require [clojure.edn :as edn]))
(defn- get-resource [path]
(let [classloader (java.lang.ClassLoader/getSystemClassLoader)]
(.getResource classloader path)))
(defn- read-config-file []
(let [url (get-resource "config.edn")]
(slurp url)))
(defn- parse-config-file [string]
(edn/read-string string))
(comment
"Example: get a nested value from the config file (config.edn on the classpath"
(env/
(defn- delayed-config []
(delay (do (println "reading configuration...")
(parse-config-file (read-config-file)))))
(def ^:private config
(atom (delayed-config)))
(defn get [& paths]
(get-in @@config paths))
(defn reload! []
(reset! config (delayed-config)))
(comment
"Example: read a value from the configuration file"
{:dbpath "file://tmp/database"}
(my.env/get :dbpath) ;=> "file://tmp/database"
"Example: read a nested value from the configuration file"
{:pool {:object {:type :special}}}
(my.env/get :pool :type :count) ;=> :specal
"Example: reload the configuration file"
(my.env/reload!)
(my.env/get :dbpath) ; reads the file again
)
@lygaret
Copy link
Author

lygaret commented Jul 30, 2015

This isn't super useful, because things like environ exist, but I didn't know that when I wrote this.

The novel (to me at the time) thing I did here was to store a delay in an atom, which means that I could memoize reading the configuration file until it's used, but still be able to force a reload (which I need, since I edit the config a good amount in development).

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