Category Archives: Clojure

ClojureScript Painkiller (for OOP)

When I learned and used ClojureScript, I really hated writing code that looks like this:

(defn Bag []
  (this-as this
           (set! (.-store this) (array))
           this))

(set! (.. Bag -prototype -add)
      (fn [val]
        (this-as this
                 (.push (.-store this) val))))

(set! (.. Bag -prototype -print)
      (fn []
        (this-as this
                 (.log js/console (.-store this)))))

(def mybag (Bag.))
(.add mybag 5)
(.add mybag 7)
(.print mybag)

That’s so much ceremony and repeated waste!

I know it’s not how you’re supposed to write ClojureScript, but sometimes you have to (for example when working with OO libraries).

What do you do with such code? Cover it with macros!

So I wrote two little macros that you can just pick up and use right away in your ClojureScript, so that it can look like:

(defn Bag []
  (this-as this
           (set! (.-store this) (array))
           this))

(set-obj-fn Bag.prototype.add [val]
            (.push (.-store this) val))

(set-obj-fn Bag.prototype.print [val]
            (.log js/console (.-store this)))

Or just a this-as shortcut:

(set! (.. Bag -prototype -add)
      (obj-fn [val]
        (.push (.-store this) val)))

Source with complete sample is on github. The library is on Clojars, so to use it all you need is [cljs-painkiller "0.1.0"] in your project.cljs. Enjoy!

Get Started with ClojureScript with Leiningen Templates

When I was about to get started with ClojureScript, I was discouraged by the fact that I apparently had to figure out so much before getting a trivial project up and running.

Eventually I learned, built and showed a minimal application running with just Leiningen and Ring, and a little bit of jQuery in ClojureScript.

Some time later Kyle Cordes showed me cljs-template. It’s a Leiningen template created by Chris Granger, also known as the guy behind Noir and Light Table. That was quite fun. All you need to get a project up and running is:

lein new cljs-template my-project
cd my-project
lein run

That’s it, you’re now running a Noir application with ClojureScript in client (jQuery included). You can start hacking at the CLJS source and see changes in browser immediately.

I soon discovered that it was a few months old, using Clojure 1.3, dated build of ClojureScript and pretty much everything. Eventually (thanks to Kyle and Raynes) I got push access to the project and updated everything, so it should be in even better shape now.

I am not sure where cljs-template is going though, with Noir itself going away. I also found one bit missing: That template is awesome to get up and running and show off a demo, but you would still need to do some manual plumbing to make such a project work for a real application (with leiningen hooks on compilation etc.).

That’s why I created another template: cljs-kickoff. Like my first steps, it’s really minimal: just Ring, lein-cljsbuild and ClojureScript. Fewer files, fewer dependencies, very easy to grasp.

To kick it off, just run:

lein new cljs-kickoff my-project
cd my-project
lein run

It will compile the ClojureScript file included in the project and start Ring server with it.

In another shell, you can run:

lein cljsbuild auto

This will start lein-cljsbuild in the auto-compile mode. Whenever the CLJS source changes, it will be automatically recompiled and the running application will pick it up after reload.

Compared to cljs-template, this template is much smaller and only uses very basic, popular and mature pieces (just Ring and CLJS). It also has all the “real” Leiningen hooks in place: CLJS compilation is included in lein run, lein jar and lein uberjar.

I hope it all makes someone’s life easier by making the first step on CLJS path as easy as possible. Happy hacking!

“ClojureScript Up and Running” (Book Review)

I’ve recently finished the “ClojureScript Up and Running” book by Stuart Sierra and Luke VanderHart. Here’s a quick review of it.

It opens with a quick introduction which attempts to present ClojureScript as the alternative to (or a matured “version” of) JavaScript. Then it immediately dives into gory technical details:

  • It shows how to set up a Leiningen project with lein-cljsbuild and explains the compilation process in detail (with all the possible parameters and modes).
  • It explains the development process – getting ClojureScript, working with browser REPL, testing, packaging for use with CLJS and plain JS applications.
  • It gives a basic introduction to the language, which really is a head-first guide to Clojure (though I suspect it’s far from enough for people who don’t know Clojure, and for those who do know it it’s no use).
  • It explains integration with JavaScript, but mostly on the level of Google Closure – exporting functions and namespaces for the world outside, or using external libraries with Closure advanced compilation.
  • It explains integration with Clojure, especially using EDN as an alternative to JSON.
  • It also introduces a few CLJS libraries (little code, just an idea of what a library does). Among others it includes C2, jayq, enfocus, core.logic, domina. Google Closure is on the list as well.
  •  

    There are many things I missed, though.

    First and foremost, it does not do enough to explain why we need ClojureScript. It does not really try to convince anyone, it’s pretty much a very technical “up and running” guide.

    It does not tell you how to write ClojureScript code. The explanation of setup, compilation and integration is great, but that’s all there is. Actually, there’s little about ClojureScript itself in the book. It’s like (unconvincingly) telling you that Java is the more robust and productive alternative to C++, showing how to use javac and Eclipse, “Hello World”, and a brief indication that there’s also JEE and Swing and this and that. I wish it had some case studies, chunks of actual ClojureScript code, some discussion of architecture, patterns, sample applications…

    One more thing I did not like is that it apparently ignores the JavaScript world (except for Google Closure). There are many rich and mature JavaScript libraries out there that solve many problems, and this book has not a word on the common ways to integrate them. I spent a good while experimenting with CLJS with Backbone, Knockout, Angular and jQuery, and it’s quite a difficult, frustrating task. I know I can write a CLJS library to do the same things that Knockout does, but I would prefer to learn how to integrate the existing library with my CLJS application to solve a real problem, or be introduced to a pure CLJS alternative that someone has already created.

    Perhaps it reflects the current state of ClojureScript – not yet very mature or stable, without mature and established libraries, patterns.

    All in all, I have mixed feelings. The book is very dense and concrete, and delivers much content on so few pages. It’s true to its title – gets you up and running, and does it very well. But then immediately leaves you alone in the woods. We are yet to see “The ClojureScript Book”.

JS Routing: Sammy vs. Flatiron Director

Having little knowledge about client-side routing in JavaScript, I decided to compare two frameworks: Sammy.js and Flatiron Director.

Scope

I’ll do the comparison on a very simple application (loosely based on a sample from Flatiron). The features I’d like to use are:

  • Routing: Routing based on hash URLs like app#/author.
  • Routing with params: Getting parameters from URLs like ?15? from app#/books/15.
  • Multiple bindings: Performing more than one action for a route (in a real app it could be routing and loading some data).
  • Default routes: Plugging in a ?default? route for all unmatched paths.
  • Listeners: Plugging in a listener – some special action to execute in addition to routing on all paths.

Code

Flatiron Director

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Flatiron Director Sample</title>
    <script src="https://raw.github.com/flatiron/director/master/build/director-1.1.6.min.js"></script>
    <script>
    var author = function () { console.log("author"); };
    var books = function () { console.log("books"); };
    var viewBook = function(bookId) { 
      console.log("viewBook: bookId is populated: " + bookId); 
    };
    var wildcard = function(route) { 
      console.log("Wildcard at: " + route);
    };
    var listener = function() { 
      console.log("Listener at: " + window.location); 
    };

    var routes = {
      '/author': author,
      '/books': [books, function() { console.log("An inline route handler."); }],
      '/books/view/:bookId': viewBook,
      '/:def': wildcard
    };

    var router = Router(routes);
    router.configure({ on: listener });
    router.init();
    </script>
  </head>
  <body>
    <ul>
      <li><a href="#/author">#/author</a></li>
      <li><a href="#/books">#/books</a></li>
      <li><a href="#/books/view/1">#/books/view/1</a></li>
      <li><a href="#/other">#/other</a></li>
    </ul>
  </body>
</html>

Sammy.js

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Sammy Sample</title>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="https://raw.github.com/quirkey/sammy/master/lib/min/sammy-latest.min.js"></script>
    <script>
    $(function() {
      var author = function () { console.log("author"); };
      var books = function () { console.log("books"); };
      var viewBook = function(bookId) { 
        console.log("viewBook: bookId is populated: " + bookId); 
      };
      var wildcard = function() { 
        console.log("Wildcard at: " + this.params['route']);
      };
      var listener = function() { 
        console.log("Listener at: " + this.params['path']);
      };

      $.sammy("#main", function() {
        this.get('#author', author);
        this.get('#books', books);
        this.get('#books/view/:id', function() {
          viewBook(this.params['id']);
          console.log("An inline route handler.");
        });
        this.get('#:route', wildcard);
        this.bind('run-route', listener);
      }).run('#');
    });
    </script>
  </head>
  <body id="main">
    <ul>
      <li><a href="#author">#author</a></li>
      <li><a href="#books">#books</a></li>
      <li><a href="#books/view/1">#books/view/1</a></li>
      <li><a href="#other">#other</a></li>
    </ul>
  </body>
</html>

Notes

So what do I think about them?

Director seems to be fairly lightweight and simple. It has no dependencies and weighs 3.7 kB. It?s almost functional programming (except for the moment when you turn it on) – you can immediately see what?s going on and what the options are.

In comparison, Sammy.js is much heavier. It depends on jQuery (32.7 kB) and it weighs 6.5 kB. It makes more assumptions: Your code needs to run after page is loaded (that?s why it?s wrapped in $.ready here). It makes you write OO code – functions have no arguments, but you get more information exposed on this.

Director supports plugging in multiple handlers to a route out of the box (you can pass an array of functions). In Sammy apparently you need to wrap them in another function.

For some reason Director seems to require URLs to have a slash, like app#/books – never app#books. Sammy does not care.

The rest you can see for yourself in the code above.

Verdict

Sammy makes me download more code, all the time I need to read documentation (“So what parameters are available here?”, “What does this object hide?”), and in the end it even makes me write more code. Look at the parameterized viewBook handler: With Director, I can add the parameter to handler function and it just works. With Sammy I need to get it from this.

At this point I have strong preference for the Director. It’s smaller and much easier to use. I like that even more because I can directly use it from ClojureScript with minimal friction. It would take quite an effort to integrate Sammy.

Using Angular.js with ClojureScript

When I wrote my last post on ClojureScript, I was really hoping someone would jump in and say: “You’re doing it wrong! Here’s how.”

I did get some interesting replies, especially on HackerNews (where that post was briefly on the front page). There really seem to be two camps here: Newbies as confused as I am, and pros who say you just have to invest the time and learn, then you may be able to make good use of some of existing JS frameworks or (better?) roll your own ClojureScript frameworks. They say it’s worth it once your codebase is big enough.

Getting Angular to Work

Anyway, Greg Weber here on my blog noted that you can actually use Angular with Closure – just need to use explicit dependency injection. So far Angular seemed to require the least work with CLJS, so I was happy to give it another shot. I also found this note on minification in Angular docs very helpful.

In the end I’ve successfully rewritten the “todo” sample application. Here’s one way to do it:

(defn add-todo [scope]
  (fn []
    (.push (.-todos scope) (js-obj "text" (.-todoText scope) "done" false))
    (aset scope "todoText" "")))

(defn remaining [scope]
  (fn [] 
    (count (filter #(not (.-done %)) (.-todos scope)))))

(defn archive [scope]
  (fn []
    (let [arr (into-array (filter #(not (.-done %)) (.-todos scope)))]
      (aset scope "todos" arr  ))))

(defn CTodoCtrl [$scope]
  (def $scope.todos (array (js-obj "text" "learn angular" "done" true)))
  
  (def $scope.addTodo (add-todo $scope))

  (def $scope.remaining (remaining $scope))

  (def $scope.archive (archive $scope))) 

(def TodoCtrl
  (array
    "$scope"
    CTodoCtrl))

The last 4 lines are equivalent of using this array syntax in JavaScript:

TodoCtrl = ['$scope', CTodoCtrl];

Another way to do it is setting the $inject property, like this:

(def TodoCtrl CTodoCtrl)
(aset TodoCtrl "$inject" (array "$scope"))

As usually, complete working project can be found at my GitHub repository.

Implementation Details

Function definition

In the above example I’m defining functions on CTodoCtrl by using “factory functions”. I find this slightly more readable, but it also can be done with in-place definitions like this:

(aset $scope "remaining" 
        (fn []
          (count (filter #(not (.-done %)) (.-todos $scope)))))

Unfortunately, I was unable to get it to work with anonymous functions (it compiled to CTodoCtrl.remaining = (function CTodoCtrl.remaining() {...):

(aset $scope "remaining" #(...))

This did not work either (I wish it did!):

(defn $scope.remaining [] (...))

Objects, Arrays

I’m not quite happy with the use of objects here – I would definitely prefer to use Clojure maps like this:

; Instead of:
; (def $scope.todos (array (js-obj "text" "learn angular" "done" true)))
; Do:
(def $scope.todos [{:text "learn angular" :done true}])
; Insetad of:
; (into-array (filter #(not (.-done %)) (.-todos scope)))
; Do:
(filter #(not (:done %)) (:todos scope))

Unfortunately, it seems Angular doesn’t like ClojureScript types and vice versa. Looks like a small, fixable annoyance.

ClojureScript!

It’s still ugly at places and not quite spectacular, but I like using functional programming with ClojureScript instead of JavaScript loops.

I mean replacing this:

var count = 0;
angular.forEach($scope.todos, function(todo) {
  count += todo.done ? 0 : 1;
});
return count;

with:

(count (filter #(not (.-done %)) (.-todos scope)))

And this:

var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function(todo) {
  if (!todo.done) $scope.todos.push(todo);
});

with:

(let [arr (into-array (filter #(not (.-done %)) (.-todos scope)))]
      (aset scope "todos" arr))

Verdict

All in all, I may finally be seeing the light at the end of the tunnel. Integration with Angular looks very promising, after addressing the small interop glitches with type mapping it may be quite expressive and straightforward. I probably will shelve Knockout for now and explore Angular.

Marrying ClojureScript and JS Frameworks – Knockout Edition

A while ago I began to play with ClojureScript and tried to get it to work with popular frameworks. I played with a few of them, most recently with Knockout.js. This post sums up those efforts and my not-so-optimistic view on ClojureScript.

  • I tried “bare” jQuery. It was pretty smooth.
  • I tried Backbone.js. I got it to work on a simple example, though one reader on Twitter rightfully commented that ClojureScript was hideous. Yes, that Backbone example is hideous. Later on I tried to do something less trivial. Eventually I fled in horror, thanks to impedance mismatch between heavily OO Backbone and non-OO ClojureScript sauced with my ignorance in CLJS (and Backbone).
  • I also gave Angular.js a shot. It started really smooth, because Angular proudly states that it doesn’t rely on object-oriented programming so much. It was great. Right to the moment when I started arguing with the compiler renaming my variables, soon followed by discovery that Angular and Closure are no go.

So, the time has come to another experiment – this time Knockout.js. I followed the official tutorial and here is what I eventually came up with.

The Page

The complete page in Hiccup looks like this. Nothing particularly exciting here.

(defn render-body []
  (hp/html5
     [:head]
     [:body
 
      [:p "First name: " [:strong {:data-bind "text: firstName"} "todo"]]
      [:p "Last name: " [:strong {:data-bind "text: lastName"} "todo"]]
      [:p "Full name: " [:strong {:data-bind "text: fullName"} "todo"]]
      
      [:p "First name: " [:input {:data-bind "value: firstName"}]]
      [:p "Last name: " [:input {:data-bind "value: lastName"}]]
      
      [:button {:data-bind "click: capitalizeLastName"} "Go caps"]
   
      (hp/include-js 
        "//ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js"
        "js/cljs.js")
      (hp/include-css "css/todo.css")
      ]))

ClojureScript

The most interesting part is the ClojureScript code. Here’s one way to do it:

(ns hello-clojurescript)

(defn app-view-model []
  (this-as this
           (set! (.-firstName this) (.observable js/ko "Bert"))
           (set! (.-lastName this) (.observable js/ko "Bertington"))
           (set! 
             (.-fullName this)
             (.computed js/ko 
               (fn []
                 (str (.firstName this) " " (.lastName this))) this))
           (set!
             (.-capitalizeLastName this) 
             (fn []
               (.lastName this (-> this .lastName .toUpperCase)))))
  nil
  )

(.applyBindings js/ko (app-view-model.))

Yes, I do need to explicitly return “nil” there. Otherwise it returns this.fullName = ..., and that breaks KO.

It works, but it’s hard to defend it in comparison to the JS equivalent:

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();    
    }, this);
    this.capitalizeLastName = function() {
        var currentVal = this.lastName();     
        this.lastName(currentVal.toUpperCase());
    };
    
}

ko.applyBindings(new AppViewModel());

Complete code can be found at my GitHub repository.

Better Way – Macro

This code can be made a lot better with a custom macro, as the one presented at StackOverflow:

(defvar name_model
    first_name (observable "My")
    last_name (observable "Name")
    name (computed (fn [] (str (. this first_name) " " (. this last_name)))))

(. js/ko (applyBindings name_model));

Now, that would be something!

… except for that defining macros in ClojureScript is harder than in plain Clojure, to the point that I haven’t gotten it to work yet.

Conclusions on ClojureScript

I spent quite a few hours poking at ClojureScript, and I have mixed feelings.

  1. It’s pretty hard to get ClojureScript to work with existing JS frameworks, mostly because using objects in CLJS requires so much ceremony.
  2. Contrary to plain Clojure, “fun” and “productive” aren’t the words that come to mind when I think of my adventures in CLJS. “Frustrating” and “intimidating” are much more appropriate. I’m constantly arguing with the compiler and trying to beat it to do the right thing, not having fun solving problems.
  3. Some stuff can be covered with macros, but all in all it feels very… rigid and constraining. I feel like every once in a while I’m bound to hit another rough corner, spend too much time on it, write another macro, and so on. All that only to bridge the gaps and make ClojureScript look more like… JavaScript. In fact, that feels like writing my own layer of macros to compile JS-like-DSL to ClojureScript.
  4. Perhaps there is a better way and I’m just doing something wrong. Maybe you’re not supposed to use those frameworks at all, but roll your own or use those few written in ClojureScript?
  5. Perhaps all of this makes little sense on such a small scale, and you need something really big to appreciate ClojureScript. You just need to invest many hours in passing the learning curve and macroing your way out. Maybe then it becomes more productive, modular and whatnot. I don’t know, in fact I have too little experience in JavaScript itself to answer such questions. I’m not very optimistic about it, though.

I am a DZone Most Valuable Blogger and JavaCodeGeek!

I’m happy to announce that at about the same time I became a DZone Most Valuable Blogger and a JavaCodeGeeks author. Some of my posts have been appearing on various blogs, community sites and aggregators for a while (especially those on Clojure and functional programming), but being invited to participate in something like these two programs is quite a new experience.

Some parts of this blog is ranting and bragging, but the main purpose has always been to learn and share knowledge. I wouldn’t have learned so much without the blog – just getting something to work is a lot easier than understanding it enough to be able to explain it to someone. We all know that the community is quite demanding. I learned the hard way that writing too shallowly, repetitively, or without proper understanding is immediately punished. On the other hand, it’s truly exhilarating to see my post mentioned by people I really admire, or make it to the front page of Hacker News.

The most rewarding part is always the comments. Not only does it mean that someone has visited the site, but also that they actually cared to read the post and share their insights or related knowledge.

Thanks, guys!

Hello, Backbone and ClojureScript

A few days ago I started learning ClojureScript. I wrote a trivial “hello world” application just to get ClojureScript to compile and execute, and later added some basic jQuery support with jayq.

The time has come to make things a little bit more interesting and add Backbone.js to the mix. I’ve never done ClojureScript or Backbone before, so I’m learning them at the same time with an interesting learning curve.

Anyway, I managed to rewrite the first two examples from Backbone docs to pure CLJS. I made some minor modifications like triggering events on button click and changing main background instead of sidebar.

Here’s my page source (with Hiccup):

(hp/html5 
  [:head]
  [:body
   [:button#clickable-event "Click to trigger an alert from basic Backbone event"]
   [:button#clickable-color "Click to change background color"]
   (hp/include-js 
     "http://code.jquery.com/jquery-1.8.2.min.js"
     "http://underscorejs.org/underscore.js"
     "http://backbonejs.org/backbone.js"
     "js/cljs.js")
   ])

As you can see, it renders a very basic page with two buttons and includes a few JS libraries.

And here’s the CLJS file mixing jQuery and Backbone:

(ns hello-clojurescript
  (:use [jayq.core :only [$]])
  (:require [jayq.core :as jq]))

; ALERT ON CLICK
; Rewrite of http://backbonejs.org/#Events
(def o {})

(.extend js/_ o Backbone.Events)

(.on o "alert" 
  (fn [msg] (js/alert msg)))

(jq/bind ($ "#clickable-event") :click 
      (fn [e] (.trigger o "alert" "Hello Backbone!")))

; MODEL WITH COLOR CHOOSER
; Inspired by http://backbonejs.org/#Model but without sidebar

(def MyModel 
  (.extend Backbone.Model
    (js-obj 
      "promptColor"
      (fn [] 
        (let [ css-color (js/prompt "Please enter a CSS color:")]
          (this-as this
                   (.set this (js-obj "color" css-color))))))))

(def my-model (MyModel.))
 
(.on my-model "change:color"
  (fn [model color]
    (jq/css ($ "body") {:background color})))

(jq/bind ($ "#clickable-color") :click 
         (fn [e] (.promptColor my-model)))

There’s a number of new things (to me) and nonobvious pitfalls. View this side-by-side with Backbone demos, and note:

  • To invoke _.extend(o, Backbone.Events), do (.extend js/_ o Backbone.Events). ClojureScript will correctly transform (.extend js/_ ...) to _.extend(...), and it will copy Backbone.Events as is (no quoting necessary)
  • To distinguish between objects and functions defined elsewhere and in CLJS, always prefix the former with js/name. Works for alert, underscore etc.
  • I had an issue with passing objects (as maps) directly to calls like Backbone.Model.extend(). Tried things like {:promptColor fn} and {"promptColor" fn} to no avail. I finally discovered (js-obj) and it did the trick, but it’s pretty cumbersome. I wonder if there’s a better way.
  • You need some extra work to use this. It has to be bound to a Clojure symbol with this-as macro.
  • On a slightly related note, I really begin to love jayq. In this example I use bare Backbone directly and struggle, and really appreciate jayq bridging the gap to jQuery. I wonder if there is a CLJS wrapper for Backbone.

All in all, it’s an interesting exercise. Just the right learning curve – stimulating, but not discouraging, regularly providing visible feedback.

As usually, complete source is at GitHub. I created a new repository for it, to keep “hello ClojureScript” as small as possible. This new demo probably will grow as I learn more Backbone.

Hello, ClojureScript! (with jQuery)

I decided to give ClojureScript a try. It did not come easy, because I found the official documentation somewhat complicated. I know there is ClojureScript One, but that project also is not as simple as it could be. I don’t want fancy functionality, noir/compojure, enlive/hiccup, and tons of other semi-relevant tools. Bare simplistic HTML and a starting hook for ClojureScript is pretty much all I need for the head start, I can add the rest later.

I was looking for something really minimal, and the first simple example on my Google search was Daniel Harper’s article. I got rid of noir, used up to date versions of libraries, and voila – it’s working!

When I had my first “hello world” alert showing on page load, I decided to make things a little bit more interesting and introduce jQuery. I found jayq from Chris Granger and decided to give it a shot. There’s also a sample app on Chris’ blog that helped me with some issues, namely figuring out how to bind events. It references a few more interesting libs (namely fetch & crate), but I’ve had enough for now. I guess I could spend the whole night chasing such references.

In the end, the interesting pieces of code are below:

project.clj (configured to compile CLJS from src-cljs to resources/public/js/cljs.js):

(defproject hello-clojurescript "0.1.0-SNAPSHOT"
  :description "FIXME: write description"
  :url "http://example.com/FIXME"
  :license {:name "Eclipse Public License"
            :url "http://www.eclipse.org/legal/epl-v10.html"}
  :dependencies [[org.clojure/clojure "1.4.0"]
                 [ring "1.1.6"]
                 [jayq "0.1.0-alpha3"]]
  :plugins [[lein-cljsbuild "0.2.8"]]
  :cljsbuild
  {
   :source-path "src-cljs"
   :compiler
   {
    :output-to "resources/public/js/cljs.js"
    :optimizations :simple
    :pretty-print true
    }
   }
  :main hello-clojurescript.core
  )

core.clj (trivial app, with Ring wrapper configured to serve JS resources):

(ns hello-clojurescript.core
  (:require [ring.adapter.jetty :as jetty]
            [ring.middleware.resource :as resources]))


(defn handler [request]
  {:status 200
   :headers {"Content-Type" "text/html"}
   :body 
   (str "<!DOCTYPE html>"
        "<html>"
        "<head>"
        "</head>"
        "<body>"
        "<p id=\"clickable\">Click me!</p>"
        "<p id=\"toggle\">Toggle Visible</p>"
        "<script src=\"http://code.jquery.com/jquery-1.8.2.min.js\"></script>"
        "<script src=\"js/cljs.js\"></script>"
        "</body>"
        "</html>")})

(def app 
  (-> handler
    (resources/wrap-resource "public")))

(defn -main [& args]
  (jetty/run-jetty app {:port 3000}))

hello-clojurescript.cljs (this one gets compiled to JavaScript):

(ns hello-clojurescript
  (:use [jayq.core :only [$ delegate toggle]]))

(def $body ($ :body))

(delegate $body :#clickable :click
          (fn [e]
            (toggle ($ :#toggle))))

Complete source code with instructions can be found at my GitHub repository.

At the moment I see the following issues:

  • I’m really green at ClojureScript. Tons to learn here!
  • The JavaScript file compiled from this trivial example is 13k lines long and weighs about 500 kb. Doh! Fine for local development on desktop, not that good for targetting mobile.
  • The official docs for ClojureScript are really… discouraging. Just like core Clojure documentation, they are pretty academic and obscure.
  • Docs for jayq are… Wait a minute, nonexistent? At least it’s a fairly thin adapter with small, comprehensible codebase.

Configuration Files in Clojure

I recently made a contribution to ghijira, a small tool written in Clojure for exporting issues from GitHub in JIRA-compatible format. One of the problems to solve there was loading configuration from file.

Originally, it used have a separate config.clj file that looked like this:

(def auth "EMAIL:PASS")
(def ghuser "user-name")
(def ghproject "project-name")
(def user-map
  { "GithubUser1" "JIRAUser1"
    "GithubUser2" "JIRAUser2"})

Then it was imported in place with:

(load-file "config.clj")

I did not like it, because it did not feel very functional and the configuration file had too much noise (isn’t def form manipulation too much for a configuration file?).

For a moment I thought about using standard Java .properties files. They get the job done, but they’re also somewhat rigid and unwieldy.

It occurred to me I really could use something similar to Leiningen and its project.clj files: Make the config a plain Clojure map. It’s very flexible with minimal syntax, and it’s pure data just like it should be.

From a quick Google search I found the answer at StackOverflow.

It turns out I can rewrite my configuration file to:

{:auth      "EMAIL:PASS"
 :ghuser    "user-name"
 :ghproject "project-name"
 :user-map
   { "GithubUser1" "JIRAUser1"
     "GithubUser2" "JIRAUser2" }
}

And then load it in Clojure with read:

(defn load-config [filename]
  (with-open [r (io/reader filename)]
    (read (java.io.PushbackReader. r))))

That’s it, just call read.

I find this solution a lot more elegant and “pure”.

By the way, this data format is getting a life of its own, called Extensive Data Notation. The Relevance team has even published a library to use EDN in Ruby.