Last active
August 29, 2015 14:26
-
-
Save lygaret/e49a4a76c3199d811a07 to your computer and use it in GitHub Desktop.
not really useful config loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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).