Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define multiple var clojure macro

I have a clojure application that need some configuration variable, mainly string but also stuff to evaluate.

I could just declare every single variable with something like:

(def config-db "URI_DB"))
(def config-time (hours 1))

But I thought that might be a good idea (I am not very sure) write a macro to do that, something that will looks like this:

(make-config 
  config-db "URI_DB"
  config-time (hours 1))

(Or I can put the names inside a vector to looks more like a let statement)

But I am getting problem when I put more than one couple, I did this:

(defmacro define-config
  [name definition]
  `(def ~name ~definition))

But I have really no glue to how expand this in something more useful...

Any suggestions or ideas ?

like image 900
Siscia Avatar asked Oct 13 '12 15:10

Siscia


1 Answers

I strongly recommend just doing each def separately. This macro is trivial but isn't very useful. When someone sees def, they know precisely what is going on. When they see your custom make-config call, they have to look at the implementation of make-config to know what is going on. You get rid of a few characters in large examples and lose readability.

With that said, you can make a macro to do this easily:

(defmacro make-config [& forms]
  `(do ~@(for [[name body] (partition 2 forms)]
           `(def ~name ~body))))

And an example of usage:

user=> (make-config foo "foo" bar (str "b" "a" "r"))
#'user/bar
user=> foo
"foo"
user=> bar
"bar"
like image 122
Rayne Avatar answered Oct 05 '22 14:10

Rayne