Thursday, November 10, 2011

ClojureScript on Rails Asset Pipeline

This post is the second part subsequent to Tilt Template for ClojureScript. Now, Tilt template for ClojureScript has worked, so the template should work with Rails asset pipeline. Though it is brief, Ruby on Rails Guides: Asset Pipeline mentions "Registering gems on Tilt enabling Sprockets to find them." So, I tried that..


To make it work, I added just one simple class, which is clementine_rails.rb below:

module Clementine
class ClementineRails < Rails::Engine
initializer :register_clojurescript do |app|
app.assets.register_engine '.cljs', ClojureScriptTemplate
app.assets.register_engine '.clj', ClojureScriptTemplate
end
end
end

That's it. Then Sprockets finds ClojureScriptTemplate.


Let's try ClojureScript on asset pipeline.


I need Rails app in any case, so I created it. Undoubtedly, my Ruby is JRuby, and is bundler/rails gems installed.
rails new rouge

Then, I added "clementine" gem (a name of ClojureScript template gem) to Gemfile. Since the gem is under development, I specified the directory of the gem.

gem 'clementine', :path => "/Users/yoko/Projects/clementine"

Then, typed bundle install so that clementine gem is recognized. I need at least one controller, so, next, I created "Greetings" controller.

rails g controller Greetings index



Well, finally, Clojure stuff comes in. I put the file below in the directory, app/assets/javascripts. The filename is hello.js.clj . This is because Rails asset pipeline strips extensions off. The file, hello.js.clj, will be used as hello.js. Perhaps, the name, "hello" , works, but it doesn't look like javascript.

(ns hello)
(defn ^:export greet [name]
(str "Hellooo " name))

Finishing touch is to add a javascript snippet to use the function defined by ClojureScript. I added three lines in app/views/greetings/index.html.erb:

<script>
alert(hello.greet("ClojureScript"));
</script>
<h1>Greetings#index</h1>
<p>Find me in app/views/greetings/index.html.erb</p>



When I started Rails and requested http://localhost:3000/greetings/index, I saw the alert box successfully!


Tentatively, I set ClojureScript's option, {:optimizations :advanced}, as default. When I looked the contents of hello.js, I confirmed it was the one ClojureScript compiled.


Although the clementine gem should be improved in various ways, ClojureScript is on Rails asset pipeline. If you are interested, watch https://github.com/yokolet/clementine.

1 comment:

Alexander Kellett said...

More articles!


p.s: heavily delayed with merging our branches, serious problems last week (not clojurescript related ;) )