Skip to content

Instantly share code, notes, and snippets.

@pandeiro
Created January 5, 2012 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pandeiro/1565647 to your computer and use it in GitHub Desktop.
Save pandeiro/1565647 to your computer and use it in GitHub Desktop.
Clutch/Noir examples
;;
;; Using this to store the CouchDB connection and put auth credentials on requests that need them
;;
(ns couch-client.client
(:require [com.ashafa.clutch.utils :as clutch]))
(defonce ^:dynamic *dbs* (atom {}))
(defn put-auth [db]
(let [credentials (select-keys (meta @*dbs*) [:username :password])]
(merge (if (instance? com.ashafa.clutch.utils.URL db) db (clutch/url db))
credentials)))
;;
;; This is a typical model used in the app. Other models have very similar functions,
;; ie get-by-author, get-by-ts, etc, only requesting from that model's DB and design doc
;;
(ns woodshed.models.story
(:use [couch-client.client :only [*dbs* put-auth]]
com.ashafa.clutch)
(:require [noir.validation :as valid]
[noir.session :as session]
[woodshed.models.user :as user]))
(declare valid?)
(def story-spec
{:_id "8e118a6547940f9028bd3e5a099f36fb"
:_rev "1-cd3aba05f772c752ef56b286c70c9004"
:story true
:published true
:tags ["clojure" "emacs" "swank" "lein"]
:title "Getting swank to work"
:slug "getting-swank-to-work"
:content "This is the story content."
:ts 1325440827348
:born 1325440827348
:mkd false
:html false
:author "273b5915184b838d3ca50bc919ccfa78"
:can-view ["0d7d124797cc1749f4d1d9ee70378817"
"393151051e41b88dfb62ed30801c378e"]
:can-edit ["0d987a112ca4032c891a7c8c7bff10a3"]
:can-comment true})
(defn get-by-slug [slug]
(-> (get-view (@*dbs* :stories) "views" :by-slug
{:include_docs true} {:keys [slug]})
first :doc))
(defn get-story [slug-or-id]
(or (get-by-slug (@*dbs* :stories) slug-or-id)
(get-document (@*dbs* :stories) slug-or-id)))
(defn get-by-ts
([] (get-by-ts nil))
([opts]
(let [defaults {:include_docs true :descending true}]
(get-view (@*dbs* :stories) "views" :by-ts
(merge defaults opts)))))
(defn get-by-author [author]
(get-view (@*dbs* :stories) "views" :by-author
{:include_docs true} {:keys [author]}))
(defn get-published
([] (get-published nil))
([opts]
(let [defaults {:include_docs true :descending true}]
(get-view (@*dbs* :stories) "views" :by-published
(merge defaults opts)))))
(defn put-story [doc]
(if (valid? doc) (put-document (put-auth (@*dbs* :stories)) doc)))
(defn valid? [{:keys [author published slug born ts]}]
(valid/rule (user/get-user author)
[:author "Must be a valid user ID to author a story"])
(valid/rule (or (not published) slug)
[:slug "Need a slug to publish a story"])
(valid/rule (some false? (map #(instance? java.lang.Long %) [born ts]))
[:born "Story needs timestamps"])
(not (valid/errors?)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment