by Dan DeMeyere - @dandemeyere
If you're a Rails developer, CoffeeScript is something you need to pay attention to. With the news that CoffeeScript will be included by default in Rails 3.1, CoffeeScript is definitely generating a sizable amount of momentum and the core Rails team believes it's the future. Knowing this, I was looking for an opportunity to use it and a clean project presented itself this sprint at thredUP. So with the help of my colleagues Kylie and Chris, we dove in and started playing away.
The first step is installing CoffeeScript. I used CoffeeScript's official installation instructions, but I ran into some weird export PATH environment issues so I installed it with Homebrew instead.
To install Homebrew, just run this command in your terminal (assuming you have xCode installed already):
Next, you need to install Node.js, which will compile your CoffeeScript for you. With Homebrew installed, all it takes is one line:
You're almost there. Just two more install commands left. The first is installing Node Package Manager and the second is using NPM to install CoffeeScript.
You can end your CS files with .coffee or .js.coffee, so create a new file in there so we can finally write some code. The project I'll be using as my example is heavily focused with DOM manipulation and since thredUP's library of choice for that is jQuery, you'll be seeing a lot of that in here.
When I first got everything setup, I was a little bit paralyzed. I didn't know where to even start. So the first thing I did was I wrote what I wanted in code in plain JS:
It's basically a setup function that calls another function which iterates over an array and logs the contents. What does this look like in CS? Like this:
Pretty sexy, right? CoffeeScript is very clean (based on Ruby and Python syntax) and it makes it much easier to work with, to read, and it's easier on the eyes. Before I get ahead of myself, there's a couple of things in this code that need to be explained, but first let's give you some resources. Syntax reference for CS can be found here. Once you're on that website, click 'Try CoffeeScript' and an interactive window appears which allows you to type CS directly into a console that the website compiles the corresponding JS right in front of you. This is what it looks like when I typed in the code above on their console:
So let's paste that code into the .coffee file you created. The next step is to compile it on your terminal:
That command will watch a specific CS file and when it detects a change, it will automatically re-compile it for you. Pretty killer, right?
This post became a lot longer than I originally intended so I broke it into two posts and I'll post the second one in a couple of days. In the next post I'll be going through using jQuery in CoffeeScript and covering if/else statements and other standard snippets of JS -> CS that you might find handy.