Coffee-script with Rails 3.x: Getting started

7 May 2011 by Jinesh Parekh 1 comment

Why should I learn Coffee-Script?

  1. Rails 3.1 is shipping with coffee script.
  2. It adds a fine syntactic sugar to java script making your code even more beautiful and terse.
  3. Easy to learn if you already are working on scripting languages such as ruby or php.
  4. If you always feared wiring inheritance in javascript, coffee-script will make it super easy for you.
  5. Being compiled to java script itself, it integrates seamlessly with your favorite javascript libraries like jquery or prototype or moo tools or anything else.

I am not going to blog about coffee scripting as it is already very well documented. However, it might help to lay down steps to quickly integrate it in your rails application. So here is the 10 minutes drill to it.

Introducing Coffee-Script in you rails 3 application

    1. Add the necessary gems to your gemfile
      gem 'coffee-script'
      gem 'barista' #It will auto compile your .coffee files into .js files.
      gem 'therubyracer', :require => nil #If you do not have nodesjs installed. Install node.js
      gem 'json'
    2. Configure barista for your application.
      rails generate barista:install
    3. Know that you have a config/initializers/barista_config.rb file for customization. You do not need to touch it yet.
    4. Create app/coffeescripts folder
    5. Add in your first coffee script file in there named with the below code:
      $(document).ready ->
      alert("Welcome to the world of coffee scripts");
    6. Copy coffee-scripts.js to your public/javascript from this link.
    7. Add coffee-script.js and welcome to your javascript includes tag
    8. Add below code in one of your erb files or application layout to see inline coffee script:
      <script type="text/coffeescript">
      firstFunction = ->
      alert('I am inline function')
    9. Start your rails app and goto http://localhost:3000
    10. Know that barista will start logging in your console window.
    11. You can also use jquery with coffee-script syntax
      <div id="effects">Test to see if it works with jQuery</div>
      <script type="text/coffeescript">
      $(document).ready ->
      $('#effects').fadeOut('slow', ->

Enjoy Coffee Scripting. Try it!

Jinesh Parekh

Founder CEO, Idyllic.

Follow me on Twitter

1 thought on “Coffee-script with Rails 3.x: Getting started”

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe To Our Blog

Get access to proven marketing ideas, latest trends and best practices.

Next up home


Lets build cool stuff

Share your contact information & we will get in touch!

I want (Tell us more about your dream project)