Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure database settings per environment

Tags:

clojure

I am using monger to fetch and save some data in MongoDb from my Clojure simple app. I have strong Ruby on Rails background so I am familiar with database settings per environment (development, test, production). I want to have something similar in Clojure. How can I add the environment to my code? I want to do it in Clojure-way, code as data, without any yaml files. I am using Leiningen if it changes something.

like image 685
Sebastian Avatar asked Apr 30 '13 10:04

Sebastian


2 Answers

You can use Leiningen profiles feature.

In your project.clj define your profiles (most cases you need dev and prod)

:profiles {:dev {:resource-paths ["resource-dev"]}
           :prod {:resource-paths ["resource-prod"]}}

Now create 2 directories resource-dev and resource-prod and create config.clj file in both of them which will have define a map to store configuration. Something like:

(ns myapp.config)
(def config {:database "dev"})

Then in your app code you can use below snippet to load the config file (only once) and access the config map:

(use 'clojure.java.io)
(def config (delay (load-file (.getFile (resource "config.clj")))))
(defn get-config []
  @(force config))

Now you can use get-config function to access the config map.

like image 188
Ankur Avatar answered Nov 14 '22 14:11

Ankur


Have a look at clj-boilerplate, a sample web app I created.

There's info in the README about how it understands environments out of the box and an example environment file can be seen here - but it looks something like this:

(def config
  (let [env (or (System/getenv "ENVIRONMENT") "development")]
    ((keyword env)
      {:development
         {:database-url "postgres://lborges:@localhost/clj-boilerplate"}
       :test
         {:database-url "postgres://lborges:@localhost/clj-boilerplate-test"
       :production
         {:database-url (System/getenv "DATABASE_URL")}})))

I have since evolved this approach but this should get you started.

Hope this helps.

like image 36
leonardoborges Avatar answered Nov 14 '22 14:11

leonardoborges