• Clojure
  • 73 lines
  • 4 forks
  • Pasted by mischov on August 13, 2013
; Automatic route gathing for compojure apps.
; Inspired by some piece of code long forgotten.
; Very rough, but it works.

(ns ...
  (:require [clojure.tools.namespace.find :as nsfind]))

(defn- find-namespaces
  "Gets all namespaces from specified directory.  A regex may be supplied as an optional second argument to filter the results."
     (find-namespaces directory #"[\s\S]*"))
  ([directory filter-regex]
     (let [namespaces (nsfind/find-namespaces-in-dir (clojure.java.io/file directory))]
       (filter #(re-find filter-regex (str %)) namespaces))))

(defn- require-namespaces
  "Requires list of namespaces."
  (dorun (map require namespaces)))

(defn- check-for-namespace
  [namespaces regex]
  (filter #(re-find regex (str %)) namespaces))

(defn- list-namespace-functions
    (require (symbol namespace))
    (map first (ns-interns (symbol namespace)))))

(defn- check-namespace-for-function
  [namespace function]
  (let [namespace-functions (list-namespace-functions namespace)]
    (some #(= (symbol function) %) namespace-functions)))

(defn- find-namespace-children
  "Finds all namespaces that are children of a certain namespace. Optionally find only children that contain a certain function."
     (find-namespaces "src/" (re-pattern (str namespace "\\.+"))))
  ([namespace function]
     (let [namespaces (find-namespace-children namespace)]
       (filter #(check-namespace-for-function % function) namespaces))))

(defn- get-function
  [namespaces function]
  (map #(ns-resolve *ns* (symbol (str % "/" function))) namespaces))

(defn functions
  "Given a parent namespace and a function name, this function gathers said function from each child namespace."
  ([namespace function]
     (let [namespaces (find-namespace-children namespace function)]
       (get-function namespaces function))))


; In randomsite/site.clj or whathaveyou that builds handler

(require [... :as include]

(def all-routes
  (apply compojure/routes
          (include/functions 'randomsite.pages 'routes)
          util-routes ; ie, resources or notfound.

; In randomsite/pages/index.clj

(cmpjr/defroutes routes
  (GET "/" [] ...))

Did you know? CLOSE

  • There are keyboard shortcuts!
    • When Creating A Paste
      • ALT+P Toggle Private
      • CTRL+Enter Create Paste
      • ALT+W Toggle word wrap
    • When Viewing A Paste
      • ALT+G Go to a line
      • ALT+CTRL+E Edit the paste
      • ALT+R Show the raw code
  • There are URL options!
    • When Creating A Paste
      • ?lang=Javascript to default to javascript
    • When Viewing A Paste
      • #L-N Jump to line number N