Created
April 5, 2013 17:45
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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