Twitter GitHub Facebook Instagram dirv.me

Daniel Irvine on building software

The CoffeeScript At Sign (@) and Teaspoon

18 August 2014

Teaspoon is a pretty great test runner for Rails. You can write CoffeeScript tests and they Just Work(TM). Teaspoon takes care of transpilation, path management, and works with the asset pipeline.

The current Quick Start Walkthrough features this example class:

class @Calculator
  add: (a, b) ->
    a + b

I immediately asked myself: why @Calculator and not Calculator? Removing the @ from in front of the class name causes Teaspoon to error with an undefined symbol error.

The answer is that Teaspoon requires types to accessible from the global object, which is window, and the at sign is a shortcut for this. which equates to window. in this context.

In other words, it’s equivalent to writing:

class window.Calculator
  add: (a, b) ->
    a + b

An intelligent way to fix this peculiarity is to introduce namespaces. For example:

MySite = {}

class MySite.Calculator
  add: (a, b) ->
    a + b

This approach kills two birds with one stone. Firstly, the definition of MySite on line one occurs implicitly on the window global object because it’s not a class definition, and so MySite.Calculator will be available to Teaspoon. Secondly, if you put all your types in the MySite namespace then you aren’t polluting the global namespace.

About the author

Daniel Irvine is a software craftsman at 8th Light, based in London. These days he prefers to code in Clojure and Ruby, despite having been a C++ and C# developer for the majority of his career.

For a longer bio please see danielirvine.com. To contact Daniel, send a tweet to @d_ir or use the comments section below.

Twitter GitHub Facebook Instagram dirv.me