Skip to content

Instantly share code, notes, and snippets.

@kikofernandez
Created April 5, 2013 17:45
Show Gist options
  • Save kikofernandez/5321189 to your computer and use it in GitHub Desktop.
Save kikofernandez/5321189 to your computer and use it in GitHub Desktop.
Small example of using sessions in Compojure using sandbar. The function is called stateful-route and is in the file handler.clj .In private.clj you can find an example of using and initializing a session using sandbar in Compojure.
(ns project-name.handler
(:require [compojure.handler :as handler]
[compojure.route :as route]
[ring.middleware.params :as params]
[sandbar.stateful-session :as session]
[project-name.controllers.private :as private]))
(defn- stateful-route
"Calls the routeFn adding stateful session."
[routeFn]
(-> routeFn
session/wrap-stateful-session
params/wrap-params))
(defroutes app-routes
;; another route for the public
(stateful-route private/routes) ; stateful route, we have an user.
(route/resources "/")
(route/not-found "Not Found"))
(def app
(handlet/site app-routes))
(ns project-name.controllers.private
(:use [compojure.core :only (defroutes GET POST context)])
(:require [project-name.models.private :as models]
[sandbar.stateful-session :as session]
[project-name.views.private :as views]))
(defn- index
;; Function with multiple arguments.
;; get from the session with session-get :user and if empty, init with a model
([] (let [user (session/session-get :user (models/user-model {:name "Kiko"}))]
(views/welcome user))) ;; a view where we display the user
([id] (let [user (session/session-get :user (models/user-model {:name "Kiko"}))]
(views/welcome user)))) ;; a view where we display the user
(defroutes controller-routes
(GET "/welcome/" [] (index))
(GET "/welcome/:id" [id] (index id)))
(defroutes routes
(context "/user" [] controller-routes))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment