Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Guestbook app
chmod +x lein
lein self-install
lein new noir guestbook
cd guestbook

#Add dependencies

edit project.clj and add jdbc dependencies

(defproject guestbook "0.1.0-SNAPSHOT"
            :description "guestbook"
            :dependencies [[org.clojure/clojure "1.3.0"]
                           [noir "1.3.0-beta3"] 
                           [org.clojure/java.jdbc "0.2.3"]
                           [org.xerial/sqlite-jdbc "3.7.2"]]
            :main guestbook.server)

run the project

lein run

update common namespace with our layout

(ns guestbook.views.common
  (:use [noir.core :only [defpartial]]
        [ :only [include-css html5]]))

(defpartial layout [& content]
     [:title "guestbook"]
     (include-css "/css/reset.css")]
     [:section#wrapper content]
     [:footer#footer "My awesome guestbook"]]))

add the main page to welcome namespace

(ns guestbook.views.welcome
  (:require [guestbook.views.common :as common]
            [guestbook.models.db :as db])
  (:use noir.core hiccup.core hiccup.form))

(defn show-guests []
  (into [:ul.guests]
        (for [{:keys [message name timestamp]} (db/read-guests)]
           [:blockquote message]
           [:p "-" [:cite name]]
           [:time timestamp]])))

(defpage "/" {:keys [name message error]}
    [:h1 "Guestbook"]
    [:p "Welcome to my guestbook!"]
    [:p error]
    (form-to [:post "/"]
             [:p "Name:" (text-field "name" name)]
             [:p "Message:" (text-area {:rows 10 :cols 40} "message" message)]
             (submit-button "comment"))))

(defn error [params error]
  (assoc params :error error))

(defpage [:post "/"] params
    (empty? (:name params )) (render "/" (error params "Some dummy who forgot to leave a name"))
    (empty? (:message params )) (render "/" (error params "THIS IS THE BEST WEBSITE EVER!"))
      (db/save-message params)
      (render "/"))))

create the database handler

(ns guestbook.models.db
  (:require [ :as sql])
  (:import java.sql.DriverManager))

(def db {:classname  "org.sqlite.JDBC",
         :subprotocol   "sqlite",
         :subname       "db.sq3"})

(defn read-guests []
    (sql/with-query-results res 
      ["SELECT * FROM guestbook ORDER BY timestamp DESC"] 
      (doall res))))

(defn save-message [{:keys [name message]}]
      [:name :message :timestamp]
      [name message (new java.util.Date)])))

and we're done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment