Last active
December 16, 2015 03:49
-
-
Save ghoseb/5373212 to your computer and use it in GitHub Desktop.
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.
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 props.core | |
(:require [clojure.string :refer [split]] | |
[clojure.java.io :refer [reader]]) | |
(:import java.util.Properties)) | |
(defn- split-key | |
"Split a string key to its subparts. | |
foo -> [foo] | |
foo.bar.baz -> [foo bar baz]" | |
[k] | |
(map keyword (split k #"\."))) | |
(defn- load-props | |
"Load a properties file to a Java Properties object." | |
[props-file] | |
(doto (Properties.) | |
(.load (reader props-file)))) | |
(defn parse | |
"Parse a properties file into a Clojure datastructure." | |
[props-file] | |
(let [p (load-props props-file)] | |
(reduce (fn [init [k v]] (assoc-in init (split-key k) v)) {} p))) | |
;;; Example: | |
;;; (parse "sample.properties") | |
;;; => {:ring {:handler {:protocol "binary", :ns "some-ring-handler-ns"}}, | |
;;; :name "configuration-clj", | |
;;; :db {:host "example.org", :name "whacko-db", :port "4567"}, | |
;;; :version "0.2.4"} | |
;;; HOMEWORK: Write function dump that'll do the opposite of parse. |
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
name = configuration-clj | |
version = 0.2.4 | |
db.name = whacko-db | |
db.host = example.org | |
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