Friday, September 10, 2010

Interactive Web Development with Clojure

Interactive web development is a rapid iteration of the following:

1. Create/edit source file. Save.
2. Compile. (not required; the runtime reloads them automatically)
3. Deploy to app server. (not required; the runtime syncs up with embedded web container)
3. Evaluate in REPL or refresh browser.

Languages like PHP, Ruby, Python etc already support this and here we discuss how to achieve the same with Clojure using the Eclipse IDE and CounterClockWise plugin. This example uses Compojure as the web development library.

Make sure you use CounterClockWise plugin version 0.0.62 or later with Eclipse: http://code.google.com/p/counterclockwise/

Create a Clojure project and define your Compojure routes like this:


(ns example.core
(:use compojure.core)
(:require [compojure.route :as route]))

(defroutes handler
(GET "/" [] "Hello World!")
(route/not-found "Page not found"))


Create another file called ipte.clj outside of the regular sources directory. Let's say we create this under a folder called dev, so the folder structure looks like this:


dev
`-- ipte.clj
src
`-- example
|-- core.clj
`-- (other files)


Now make sure both src and dev folders are included as source folders in Eclipse. Edit the file ipte.clj to contain the following:


(ns ipte "In-process Test Environment"
(:use ring.adapter.jetty)
(:use example.core))

(defonce server
(run-jetty (var handler) {:port 8080}))


Note:
1. The file ipte.clj starts Jetty server on compile/reload, so it's put in a separate file (for development environment only).
2. defonce makes sure the Jetty server is not attempted to start again upon namespace reload. Using _ as var name with defonce resulted in non-evaluation of the expresion for me, so I would suggest using a proper name.
3. (var ..) makes sure that updates to the handler data is available across namespace reloads.

Make sure you include all required JAR files in project classpath and we are all set up (leaving out a required JAR may lead to silent failure while running the project in Eclipse). Right-click on the project (root node) in left package/navigation pane and select "Run in JVM". That's all. Now, the changes you make to the source code will reflect in the REPL or browser immediately.

2 comments:

  1. Most of the time I don’t make comments on websites, but I'd like to say that this article really forced me to do so. Really nice post!

    ReplyDelete
  2. Great post . It takes me almost half an hour to read the whole post. Definitely this one of the informative and useful post to me. Thanks for the share and plz visit my site Design and multimedia 21st and century provide offshore outsourcing service, freelance service, personal assistant,web development, customer service, marketing services.






    ReplyDelete

Disqus for Char Sequence