Private members in coffeescript and the query string

Because coffeescript is really just a thin veneer over javaScript there are, in my opinion, a few lost opportunities. For example, when you create a class all members (properties or functions) are public. However, there are work arounds.

I created a class to help me work with query string parameters. Actually, I ended up creating two classes, one an implementation class that did most of the hard work, and another to act as the public interface to the rest of the world. The “public” class is attached to the window object to make it globally available within the browser, the implementation class will only be available to other code inthe same script as the script as a whole will be wrapped by the coffeescript compiler in an anonymous function.

The publically available class, the one attached to the window object exposes three functions, yet it doesn’t expose its association to the implementation class. I achieved this by making the the association to the implementation class inside the constructor and then definining all the other functions in the construtor too. Each method I wanted to make public I prefixed with the @ symbole (the equivalent of this. so that it would be available to users of the class

# Define the queryString class, attaching it to the window object,
# effectively making it globally available.
class window.queryString
  constructor: (url) ->
    # The constructor defines a local variable to hold the reference
    # to the implementation class. This acts as a private member variable.
    __qsImpl = new queryStringImpl(url)

    # The public methods are defined on "this" by using the @ prefix
    # They can access the local variables in the parent scope because
    # they are closures.
    @getValue = (key) ->
      result = __qsImpl.params[key]
      if not result?
        result = __qsImpl.canonicalParams[key.toLowerCase()]
      return result

    @count = () ->

    @hasKey = (key) ->
      return key of __qsImpl.params || key.toLowerCase() of __qsImpl.canonicalParams

The implementation class also detects when the url is null or undefined and automatically finds the url and extracts the query string information for you. With this you can then get access to the query string parameters by using code like this:

# Create the query string object
qs = new queryString()

# Get a value from the query string
theValue = qs.getValue("SomeQueryStringKey")

# Work out if a value is available on the query string
isAvailable = qs.hasKey("SomeQueryStringKey")

# Find the number of query string parameters
numberOfParams = qs.count()

Classes, static properties, and inheritance in Coffeescript

I fear the documentation for coffeescript does not really explain the way that static and instance members work terribly well. So, I’ve put together this rough guide to classes in coffeescript

For this set of examples, I’m going to use my standard class diagram that you may have seen on other blog posts:

Creating a class

To create a class you simply write

class Animal

However, the way coffeescript works is that class will only be accessible to other things in that script. The command line utility does allow lots of files to be joined together so that may not be such an issue for the most part. However, if you want your class accessible on the page you are going to have to make it globally available in which case you will need to attach it to the window, like this:

class window.Animal

The class constructor

At its simplest the constructor can be as simple as this:

class Animal
  constructor: ->

The above construct takes no arguments and doesn’t do anything. There is no body. Note, that since coffeescript has significant white-space the constructor method has to be indented. To ensure that it is empty, don’t put the next line of code in at a greater indent depth that the word “constructor”

If the constructor doesn’t need to do anything you can leave it out. If you do need to initialise things then you can. For example, let’s say we want each animal to know its date of birth, we can do this

class Animal
  constructor: (dateOfBirth) ->
    @born = dateOfBirth

The @ symbol is a shorthand for this. However, there is an even quicker way of doing this. If your argument is simply going to be assigned to an instance variable, then you could do this instead:

class Animal
  constructor: (@born) ->

Static members

This is one area I find somewhat confusing. If you want to declare a static field on a class, you prefix it with the @ symbol, as if you are creating a short hand for this. Which is, in fact, what you are doing.

class Animal
  @population : 0

In the context of the class, the use of this is correct. You are operating int he context of an object of type class. Not an object of an instance of that class. If that makes sense. Essentially, the class itself is an object.

So, if you want to use this static variable on the class you could do something like this

class Animal
  @population : 0

  constructor: (@born) ->
    Animal.population += 1

And from outside the class, you similarly reference the class itself. For example:

(new Animal 'Today') for count in [1..10]
currentPopulation = Animal.population

Similarly, static methods on the class are prefixed with the @ symbol. For example

  @resetPopulation: () ->
    Animal.population = 0

And called on the class, rather than an instance. Also remember that if the method has no parameters, you need to include the parenthesis in the call, otherwise it gets itself in a bit of a twist. e.g.



To inherit from a class you simply extend the base class. For example:

class Mammal extends Animal

If your base class has a constructor then it will be called automatically when you instantiate the derived class. However, if you need to add a constructor of your own to the derived class you must remember to call the base constructor manually otherwise the base construction won’t happen as you expect.

class Animal
  @population : 0

  constructor: (@born) ->
    Animal.population += 1
    @isMulticellular = "no"
    console.log 'Animal constructor called. Population is '+Animal.population

class Mammal extends Animal
  constructor: (born) ->
    @isMulticellular = "yes"
    console.log 'Mammal constructor called.'

If you note, the call to super (to call the base constructor) happens first. This is generally what happens in many object oriented languages when constructing classes that have inheritance. The base parts of the class are constructed first. This gives the derived class access to the fully constructed base parts before it does its part. However, you are free to put the call to super anywhere in the derived class’s constructor.

Loading coffeescript unit tests from separate files

In my previous post I showed how to create unit tests for coffeescript. I also included a link to Eli Thompson’s coffeescript unit testing runner which allows you to easily gather all the .coffee files and the unit tests together in one place thus allowing you to keep your unit tests in separate files (rather than in-lining it in the test-runner as I showed in my previous example).

So far, so good. However, you cannot run this from the local file system as the browser’s security will complain (see the console panel in the screenshot below). The files are loaded using jQuery’s get method.

So, in order to get it to run you need to run it from within the context of a web server. You can use IIS if you are running windows, however for this example, I’m using Linux so I’ll use Apache.

Getting Apache up and running on Linux

To install Apache, in a terminal type:

sudo apt-get install apache2

By default, the newly installed server will serve from the /var/www/ which will contain an index.html already.

In order to create a new site that points to your development environment so that you can run the unit tests locally you need to modify apache.

Start by opening the /etc/apache2/apache2.conf file. (You’ll need to use sudo or run as root in order to write this back as your user won’t have the permission by default.) And add the following to the end of the file:


This tells Apache that you’ll be creating named web sites on the IP/port specified. This is most useful if you have a server that hosts multiple sites. In our case we are simply using it to create a development site on our local machine. Because we’ve specified the loopback address it won’t be visible outside of the machine it is running on. (More info on NameVirtualHost)

Next we have to create a file in /etc/apache2/sites-available/ directory. As far as I can see, the convention is to use the host name as the name of the file. So a site running a would have a file of the same name. In this case, as it is a development site running only on localhost I like to name it something along the lines of myproject-localhost so that it is obvious that it is running on the loop back address.

For this example, I’ll create a file called /etc/apache2/sites-available/coffee-tests-localhost with the following content:

ServerName coffee-tests-localhost
DocumentRoot /home/colinmackay/hg/blog-and-demos/three-of-a-kind

Since this file is in sites-available that means it is not yet enabled, so the server won’t be serving it up. In order to get it served up there needs to be a duplicate in /etc/apache2/sites-enabled/. You don’t need to create a duplicate in Linux as you can create a symbolic link to the original file. To do that, type the following at a terminal:

cd /etc/apache2/sites-enabled/
sudo ln -s ../sites-available/coffee-tests-localhost .

(Note the dot at the end of the second line!)

Since the host name does not really exist, no DNS will resolve it, this is the point that you need to edit the /etc/hosts file so that your local browser can go to the web site. Add the following line to the hosts file:     coffee-tests-localhost

Finally restart the Apache server:

sudo /etc/init.d/apache2 restart

You should now have your web site up and running and displaying the tests to you now.

The running tests

When we go to http://coffee-tests-localhost/tests/test-runner.htmlall the tests now run and there is no error in the browser’s console:

More information

Unit testing with Coffeescript

I’ve recently started  looking at Coffeescript. And to get going with that I’m jumping directly in with unit-testing. I figured that it would be an interesting way to learn the language.

Since coffeescript compiles to javascript, you can use a javascript unit testing framework such as QUnit which can be downloaded from github.

Getting to grips with QUnit

Before we delve into coffeescript part, let’s have a very quick look at QUnit.

In order to run unit tests create an HTML page that will contain the runner. In this page you need to include jQuery, and QUnit ( and The body of your test runner needs to contain elements that QUnit will update during the tests. You also need to include the tests themselves.

I won’t go much further in to QUnit as there is already ample
information about getting going with QUnit over on the jQuery website.

Running coffeescript in the browser

Normally coffeescript is pre-compiled into javascript before being sent to the browser, however it is possible to have the browser compile coffeescript itself. This would not be recommended for production code, but does make life easier for running unit tests as the browser handles the compilation step for you.

You can run coffeescript in the browser by using the script located at Then
any subsequent script blocks that are marked with the text/coffeescript type will be compiled on-the-fly. e.g.

<script type="text/coffeescript">
    // Your coffee script code here

One annoyance I’ve found is that coffeescript relies on “significant whitespace” which means that I’m forced to format my code the way coffeescript likes. In general thats not necessarily a bad thing, especially when you are editing coffeescript files, but with inline script blocks it can be irritating. Your script block may already be indented (and I tend to go for indents of two spaces for HTML files, as opposed to 4 for C#) which coffeescript doesn’t seem to like.

Running some tests

First of all this is what a test looks like in javascript using QUnit.

  <script type="text/javascript">
        module("My javascript test");

        test("Assert 1 not equal 0", function(){
          ok(1!==0, "One expected to not equal zero");

What’s happening above is that the tests run when jQuery is ready. In other words, once the DOM is loaded. (See also: $(document).ready()).

The module method is simply a way of segregating the tests in to groups. All tests that follow a call to module will be grouped into that “module”.

The test happens in the call to test which normally takes a string which is the text to display each time the test is run, and a function containing the actual test. The second test that I have is written in coffee script.

<script type="text/coffeescript">
    module("My coffeescript test");
    test("Assert 1 equals 1", ()-> ok(1==1, "One expected to equal one"));

While in coffeescript you don’t need the brackets around the function parameters, I prefer them. Nor do you need the semi-colon to terminate each statment, and again this is personal preference. You’ll see lots of coffeescript that won’t use brackets and semi-colons in the above situations.

Here is the result of the two tests above:

Test 	    runner with passing tests

In both tests above there is a call to ok which asserts that the condition passed in as the first argument is true, if not it fails the test. When a test fails the text in the second parameter of the ok function is displayed. For example, a test designed to deliberately fail:

    test("Assert 2 equals 3", () -> ok(2==3, "2 expected to equal 3"));

And the result in the test runner:

Test runner with failing test

Unit testing with .coffee files

Eli Thompson has an example of how you might want to put together unit tests for a
system written in coffeescript
. The core of his example is to define a list of coffeescript files and a list of tests and have a bit of coffeescript dynamically load them in order to run the tests.

In that example, scriptsToTest contains a list of coffeescript files that contain the code to test, and a list of tests which reference the files that contain the actual tests. The code then loads each coffeescript file, compiles it to javascript and loads it into the DOM so that the browser can execute it. The code that does all the hard work is a rather elegant 9 lines of
coffeescript (not including the declaration of the files involved).

More information

This was a very quick introduction to unit testing with QUnit and
using coffeescript. Here are links to more resources to continue