Re: defroutes with common suffix

40 views
Skip to first unread message

James Reeves

unread,
Mar 12, 2013, 7:26:24 AM3/12/13
to Compojure
Functions only return the last expression evaluated, so if you have a function like:

  (defn foo []
    1
    2
    3)

Then the function will return 3. The same principle applies with routes, which are just anonymous functions: only the last one will be returned from the function.

In order to return more than one route, you need to combine them into a bigger route. Compojure has a function to do this, called "routes". This function is also the one used by the "defroutes" macro, which is literally the combination of "def" and "routes", in the same way that "defn" is the combination of "def" and "fn".

So you could write:

  (defn route-from-to [uri f]
    (routes
     (GET (str uri ":id") [id]
       (default-json-page f id))
     (GET (str uri ":id/:from/:to") [id from to]
       (default-json-page f id from to))))

Or if we want to make use of the context macro:

  (defn route-from-to [uri f]
    (context uri
     (GET "/:id" [id]
       (default-json-page f id))
     (GET "/:id/:from/:to" [id from to]
       (default-json-page f id from to))))

- James



On 12 March 2013 10:40, Zhemin Lin <lin.z...@gmail.com> wrote:
Hi.

I'm new to Compojure.  Pardon me for the novice question.
I'd like to make a function or a macro to build several routes with common suffixes.
But neither of my trials worked.

Trial 1: defn
(defn route-from-to [uri fn]
  (GET (str uri ":id") [id]
       (default-json-page fn id))
  (GET (str uri ":id/:from/:to") [id from to]
       (default-json-page fn id from to)))
(defroutes api-route
  (route-from-to "/access/"          data/my-acc))

Trial 2: defmacro
(defmacro route-from-to [uri fn] 
  `(GET (str ~uri ":id") [~'id]
       (default-json-page ~fn ~'guid))
  `(GET (str ~uri ":id/:from/:to") [~'id ~'from ~'to]
       (default-json-page ~fn ~'id ~'from ~'to)))
(defroutes api-route
  (route-from-to "/access/"          data/my-acc))

Definitely, trial 1 won't do.  It returns the latter (GET), hence only /access/id/from/to works and /access/id does not.
But trial 2 failed as well.

How to make it work?

Thanks a lot!
Zhemin.

--
You received this message because you are subscribed to the Google Groups "Compojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email to compojure+...@googlegroups.com.
To post to this group, send email to comp...@googlegroups.com.
Visit this group at http://groups.google.com/group/compojure?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Zhemin Lin

unread,
Mar 12, 2013, 8:33:07 PM3/12/13
to comp...@googlegroups.com
Cool!  (defn routes) is elegantly written!
Thank you!
Reply all
Reply to author
Forward
0 new messages