Posterous theme by Cory Watilo

How to use CoffeeScript in Rails 3.1 with Haml

I'll explain briefly how CoffeeScript is used in Rails 3.1. First create the gemset with RVM (you are using it right??!) in a test directory:

rvm --create --rvmrc default@example_app

Install Rails 3.1:

gem install rails -v=3.1.0.beta1 --no-ri --no-rdoc

Generate a new app including jQuery (shipped by default in 3.1):

rails new example_app -j

Add coffee-script and haml gems to Gemfile and run Bundler:

gem 'coffee-script'
gem 'haml'

If you see the layout file, Erb or Haml if you already converted it, the include for javascripts refers only to 'application'. And you don't need anything other in Rails 3.1. Sprockets will automagically include in application.js (with the aid of the gem jquery-rails) the concatenation of:

  • jQuery;
  • rails.js;
  • any javascript file present in app/assets/javascripts;
  • any compiled javascript from the coffeescripts living in app/assets/javascripts.

Now try to generate a scaffold:

rails g scaffold post title:string body:text

You can see that aside from the usual stuff, some assets were generated, with the new integrated CoffeeScript format (no need for the barista gem):

invoke assets
  app/assets/javascripts/posts.js.coffee
  app/assets/stylesheets/posts.css.scss

OK, now example of CoffeeScript, that you can try to run by writing it in posts.js.coffee and then firing up /posts in your browser:

If you then look at the source code of the page and open application.js you see Sprockets puts jQuery and concatenates all the javascripts!

For in page CoffeeScript with Haml, like when you use the command javascript_tag: use coffee-filter. Add coffee-filter to Gemfile:

gem 'coffee-filter'

Then use CoffeeScript interpolation to get Ruby variables inside CoffeeScript blocks, i.e.:

What if I want to release my Javascript without views... well, there isn't a way in Rails, just use a Rake task. My example, using closure-compiler gem to compress the code, no need for barista:

Then from the Rails root:

rake release:js

Well... great job Rails team!

| Viewed
times
Filed under: