Using CoffeeScript in Rails

Darcy Laycock
Darcy Laycock
Share

First released in 2009 and still under constant development, CoffeeScript is an alternative syntax for writing JavaScript that is quickly gaining popularity. Because it compiles down to JavaScript (versus assembly or some other bytecode like many languages), CoffeeScript is already useable in browsers that support JavaScript and on platforms like node.js.

Today I’ll show you how to add CoffeeScript to a Rails application—in this case, we’ll continue building on our “shorty” url shortener from my Building Your First Rails Application series—to add some basic JavaScript using CoffeeScript and Barista, a gem to add seamless CoffeeScript support to Rails applications.

Getting Started

To get started with Barista, we first need to add the required gems to our Gemfile. Hence, open up said file and add:

gem 'barista'

If you’re on Ruby 1.8.7 or lower, you’ll likely need to also add the JSON gem to your Gemfile as:

gem 'json'

Lastly, you’ll need a JavaScript interpreter to run the CoffeeScript compiler. If you’re on OSX the Ruby wrapper (shipped in the coffee-script gem) will use the built in system interpreter but if you’re on another platform, you’ll want to check the ExecJS README which goes over the options available. One simple option is to embed v8 into your application by adding the following to your Gemfile:

gem 'therubyracer', :require => nil

Next, run the following which will force bundler to update the gems, making them available to your Rails application and will then generate a configuration for barista:

bundle install
rails g barista:install

Opening up config/initializers/barista_config.rb, you should now see a set of options which let you configure how barista works—Feel free to have a look around. Next we’ll start using Barista to add CoffeeScript to our application.

Writing Some Code

For this post, we’re going to do something relatively simple using CoffeeScript. Using jQuery, we’ll embed an iframe to preview the url below the text entry.

The first thing we need to do to do is remove the existing JavaScript files and replace them with jQuery. To do this, we’ll add the following to our Gemfile:

gem 'jquery-rails'

And then run:

bundle install
rails g jquery:install

If it asks about a conflict, respond with ‘yes’ so the existing files are over-written (you are using an SCM, right?) This will tell Rails to use jQuery instead of Prototype for your application.

Next, open app/coffeescripts/shorty.coffee in your text editor (you may have to make the folder first) and add the following code:

$(document).ready ->
  preview = $("#preview-url")
  $('#url_url').keyup ->
    current_value = $.trim @value
    if current_value is ''
      preview.hide().attr 'src', ''
    else
      preview.show().attr 'src', current_value

This code is our implementation – When we change the url text fields value, it will automatically update the iframe. Next, open application/views/layouts/application.html.erb and change:

<%= javascript_include_tag :defaults %>

To

<%= javascript_include_tag :defaults, 'shorty' %>

This will tell Rails to also include the shorty JavaScript file (automatically compiled from your shorty.coffee file in the page).

Finally, we need to add the actual iframe to the page. In the new url view (app/views/urls/new.html.erb), add the following code to the bottom of the page:

<iframe id='preview-url' style='width: 600px; height: 400px; display: none'></iframe>

Note: For demonstration purposes, we’ve set the CSS inline. Typically, you’d do so in a normal css stylesheet.

Finally, save all the files and start the web server up again using rails server.

Opening your browser, you should now be able to visit http://localhost:3000/ and the page should load as expected. Start typing and you’ll see it automatically shows / hides the url as it attempts to load it as soon as possible. As you can see, Barista automatically took care of compiling the CoffeeScript file to a JavaScript equivalent for us in the background and will do so whenever the file is changed.

If you open and look at public/javascripts/shorty.js, you’ll see that using the CoffeeScript compiler, Barista has automatically converted the code above to something similar to:

/* DO NOT MODIFY. This file was compiled Wed, 13 Apr 2011 01:10:20 GMT from
 * /path/to/your/app/app/coffeescripts/shorty.coffee
 */

(function() {
  $(document).ready(function() {
    var preview;
    preview = $("#preview-url");
    return $('#url_url').keyup(function() {
      var current_value;
      current_value = $.trim(this.value);
      if (current_value === '') {
        return preview.hide().attr('src', '');
      } else {
        return preview.show().attr('src', current_value);
      }
    });
  });
}).call(this);

Debugging Issues

If the above didn’t work for you, there are a few things to check. Look at your application log and look for barista-related error messages. The most common issues you’ll find:

  • Compilation failed due to a missing compiler
  • If you’re deploying to somewhere else (e.g. Heroku), you may have to either embed an interpreter like V8 (via the gem therubyracer) or commit the generated JavaScript to your repository

Going back to the getting started steps, check out the ExecJS link again and you’ll find out the alternative JavaScript hosts.

Taking It Further

Now that you’ve got the basics supported, I suggest going off on your own and having a bit of a play around. As you can see, because CoffeeScript is compiled to JavaScript we can use all our existing libraries like jQuery with minimum effort, making it simple to use jQuery and your own JavaScript to:

  • Make it so that urls are only loaded if they ‘look valid’ (e.g. the current version attempts to preview everything)
  • Use a timer / some other method of detecting changes to avoid changing it every single time we type a character
  • Expand out the URLs to use something like Embed.ly to preview the content

To learn a bit more about CoffeScript, read through the excellent interactive tutorial on the CoffeeScript site to get a feel for how it handles conversions.

If you do add more features, comment below and let us know how you went about it / how you found the process.

Frequently Asked Questions (FAQs) about Using CoffeeScript in Rails

Why is CoffeeScript recommended in Rails?

CoffeeScript is recommended in Rails due to its simplicity and readability. It’s a little language that compiles into JavaScript, and it aims to expose the good parts of JavaScript in a simple way. The syntax is more straightforward, making it easier to write and read. It also has some additional features that JavaScript doesn’t have, which can make your code more efficient. However, it’s worth noting that the use of CoffeeScript is not mandatory in Rails, and you can use plain JavaScript or any other JavaScript preprocessor if you prefer.

How do I install CoffeeScript in Rails?

To install CoffeeScript in Rails, you need to add the coffee-rails gem to your Gemfile. This gem provides CoffeeScript compilation and a coffee generator for Rails. After adding the gem, run bundle install to install it. Then, you can use CoffeeScript in your Rails application.

How do I convert my JavaScript files to CoffeeScript in Rails?

Converting JavaScript files to CoffeeScript in Rails is straightforward. You just need to change the file extension from .js to .coffee. Then, you can start writing CoffeeScript code in the file. The Rails asset pipeline will automatically compile the CoffeeScript code into JavaScript when the page is loaded.

Can I use CoffeeScript and JavaScript together in Rails?

Yes, you can use both CoffeeScript and JavaScript together in Rails. The Rails asset pipeline supports multiple JavaScript preprocessors, so you can have some files in CoffeeScript and others in plain JavaScript. The compiled JavaScript code from all files will be combined and minified in production.

How do I debug CoffeeScript code in Rails?

Debugging CoffeeScript code in Rails is similar to debugging JavaScript code. You can use the browser’s developer tools to inspect the compiled JavaScript code. If you have source maps enabled, you can even see the original CoffeeScript code in the developer tools. You can also use console.log statements in your CoffeeScript code for simple debugging.

What are the advantages of using CoffeeScript over JavaScript in Rails?

CoffeeScript offers several advantages over JavaScript in Rails. The syntax is cleaner and more readable, which can make your code easier to maintain. It also has some additional features, like array comprehensions and destructuring assignment, which can make your code more efficient. However, whether you should use CoffeeScript or JavaScript depends on your personal preference and the requirements of your project.

How do I use CoffeeScript classes in Rails?

You can define classes in CoffeeScript using the class keyword, similar to how you would in JavaScript. You can also define methods and properties on the class. When the CoffeeScript code is compiled into JavaScript, the class will be converted into a constructor function with prototype methods.

Can I use CoffeeScript in Rails without the asset pipeline?

Yes, you can use CoffeeScript in Rails without the asset pipeline. You can compile CoffeeScript files into JavaScript using the coffee command-line tool, and then include the compiled JavaScript files in your Rails views. However, this approach requires manual compilation and does not take advantage of the automatic compilation and minification provided by the asset pipeline.

How do I use CoffeeScript modules in Rails?

You can define modules in CoffeeScript using the module keyword, similar to how you would in JavaScript. You can also export and import functions and variables between modules. When the CoffeeScript code is compiled into JavaScript, the modules will be converted into IIFE (Immediately Invoked Function Expression) with exports and imports.

What are some best practices for using CoffeeScript in Rails?

Some best practices for using CoffeeScript in Rails include keeping your CoffeeScript files small and focused, using classes and modules to organize your code, and taking advantage of CoffeeScript’s features like array comprehensions and destructuring assignment. You should also make sure to test your CoffeeScript code, just like you would with JavaScript code.