Introduce monger.core/connect! and monger.core/set-db!

Even though it is not idiomatic Clojure to mutate vars like this,
it is very common for many applications to only use one MongoDB
connection (so, no per-thread var rebinding) and one main database.

For those cases, these function eliminate the need for mundaine
hacks with namespace switching.
This commit is contained in:
Michael S. Klishin 2011-09-19 12:14:48 +04:00
parent a6d96da5bd
commit 5e12f9aec2
2 changed files with 14 additions and 4 deletions

View file

@ -48,6 +48,7 @@
([{ :keys [host port] :or { host *mongodb-host*, port *mongodb-port* }}] ([{ :keys [host port] :or { host *mongodb-host*, port *mongodb-port* }}]
(Mongo. ^String host ^Long port))) (Mongo. ^String host ^Long port)))
(defn ^DB get-db (defn ^DB get-db
"Get database reference by name. "Get database reference by name.
@ -61,6 +62,16 @@
(.getDB connection name))) (.getDB connection name)))
(defn connect!
^Mongo [& args]
(def ^:dynamic *mongodb-connection* (apply connect args)))
(defn set-db!
[db]
(def ^:dynamic *mongodb-database* db))
(defprotocol Countable (defprotocol Countable
(count [this] "Returns size of the object")) (count [this] "Returns size of the object"))

View file

@ -4,9 +4,8 @@
(:use [clojure.test])) (:use [clojure.test]))
(monger.util/with-ns 'monger.core (monger.core/connect!)
(defonce ^:dynamic *mongodb-connection* (monger.core/connect)) (monger.core/set-db! (monger.core/get-db "monger-test"))
(defonce ^:dynamic *mongodb-database* (monger.core/get-db "monger-test")))
(deftest connect-to-mongo-with-default-host-and-port (deftest connect-to-mongo-with-default-host-and-port