Skip to content

Instantly share code, notes, and snippets.

@ghoseb ghoseb/props.clj
Last active Dec 16, 2015

What would you like to do?
A simple problem that I solved at the April '13 meetup of Pune Clojure Users' Group. The problem is about parsing a Java properties file into Clojure & back.
(ns props.core
(:require [clojure.string :refer [split]]
[ :refer [reader]])
(:import java.util.Properties))
(defn- split-key
"Split a string key to its subparts.
foo -> [foo] -> [foo bar baz]"
(map keyword (split k #"\.")))
(defn- load-props
"Load a properties file to a Java Properties object."
(doto (Properties.)
(.load (reader props-file))))
(defn parse
"Parse a properties file into a Clojure datastructure."
(let [p (load-props props-file)]
(reduce (fn [init [k v]] (assoc-in init (split-key k) v)) {} p)))
;;; Example:
;;; (parse "")
;;; => {:ring {:handler {:protocol "binary", :ns "some-ring-handler-ns"}},
;;; :name "configuration-clj",
;;; :db {:host "", :name "whacko-db", :port "4567"},
;;; :version "0.2.4"}
;;; HOMEWORK: Write function dump that'll do the opposite of parse.
name = configuration-clj
version = 0.2.4 = whacko-db =
db.port = 4567
ring.handler.ns = some-ring-handler-ns
ring.handler.protocol = binary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.