Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I implement functionality similar to Rails' url_for with Clojure and its web frameworks?

I'm developing a web application with Clojure, currently with Ring, Moustache, Sandbar and Hiccup. I have a resource named job, and a route to show a particular step in a multi-step form for a particular job defined like this (other routes omitted for simplicity):

(def web-app
  (moustache/app
   ;; matches things like "/job/32/foo/bar"
   :get [["job" id & step]
         (fn [req] (web.controllers.job/show-job id step))]))

In the view my controller renders, there are links to other steps within the same job. At the moment, these urls are constructed by hand, e.g. (str "/job/" id step). I don't like that hard-coded "/job/" part of the url, because it repeats what I defined in the moustache route; if I change the route I need to change my controller, which is a tighter coupling than I care for.

I know that Rails' routing system has methods to generate urls from parameters, and I wish I had similar functionality, i.e. I wish I had a function url-for that I could call like this:

(url-for :job 32 "foo" "bar")
; => "/job/32/foo/bar"

Is there a Clojure web framework that makes this easy? If not, what are your thoughts on how this could be implemented?

like image 429
Gert Avatar asked Mar 13 '12 06:03

Gert


2 Answers

Noir provides something similar. It's even called url-for.

like image 103
Matthias Benkard Avatar answered Oct 18 '22 19:10

Matthias Benkard


The example function you have mentioned could be implemented as below. But I am not sure if this is exactly what you are looking for.

(defn url-for [& rest]
    (reduce 
        #(str %1 "/" %2) "" (map #(if (keyword? %1) (name %1) (str %1)) rest)))
like image 24
Ankur Avatar answered Oct 18 '22 19:10

Ankur