Skip to content

Instantly share code, notes, and snippets.

@ithayer
Created July 4, 2011 19:20
Show Gist options
  • Save ithayer/1063814 to your computer and use it in GitHub Desktop.
Save ithayer/1063814 to your computer and use it in GitHub Desktop.
Clojure on Heroku with Noir and Mongo Demo
# Install latest version of noir.
lein install noir "1.1.0-SNAPSHOT"
# Create new noir project.
lein noir new noir-mongo-heroku
cd noir-mongo-heroku
# Create instructions for heroku.
echo 'web: lein run' > Procfile
# Create git repository.
git init
git add .
git commit -m "Initial commit"
# Initialize heroku app.
heroku create --stack cedar
# Push to heroku.
git push heroku master
# 1. Install lein
wget https://raw.github.com/technomancy/leiningen/stable/bin/lein
sh lein
# 2. Install heroku gem
gem install heroku
# Configure Heroku to add a small mongo add on for our app.
heroku addons:add mongohq:free
(ns noir-heroku.views.welcome
(:require [noir-heroku.views.common :as common]
[noir.content.pages :as pages])
(use noir.core
hiccup.core
hiccup.page-helpers)
(:use somnium.congomongo)
(:use [somnium.congomongo.config :only [*mongo-config*]]))
(defn split-mongo-url [url]
"Parses mongodb url from heroku, eg. mongodb://user:pass@localhost:1234/db"
(let [matcher (re-matcher #"^.*://(.*?):(.*?)@(.*?):(\d+)/(.*)$" url)]
(when (.find matcher)
(zipmap [:match :user :pass :host :port :db] (re-groups matcher)))))
(defn maybe-init []
"Checks if connection and collection exist, otherwise initialize."
(when (not (connection? *mongo-config*))
(let [mongo-url (get (System/getenv) "MONGOHQ_URL")
config (split-mongo-url mongo-url)]
(println "Initializing mongo @ " mongo-url)
(mongo! :db (:db config) :host (:host config) :port (Integer. (:port config)))
(authenticate (:user config) (:pass config))
(or (collection-exists? :firstcollection)
(create-collection! :firstcollection)))))
(defpage "/welcome" []
(maybe-init)
(let [counter
(fetch-and-modify
:firstcollection
{:_id "counter"}
{:$inc {:value 1} }
:return-new true :upsert? true)]
(common/layout
[:p (str "Welcome to noir-heroku, you're visitor " (:value counter))])))
wget https://gist.github.com/1063814.js?file=welcome.clj -O src/noir_heroku/views/welcome.clj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment