Visible Whitespace in Sublime Text 2

17 May 2013

I have been using jshint in my node projects lately. Jshint is a linting tool based on JSLint by Douglas Crockford, the ghost whisperer of javascript and author of JavaScript: The Good Parts. I prefer JSHint as it is a little more configurable and I can fine tune it to what I care about.

One thing I care about is trailing whitespace. For whatever reason, I don’t want trailing whitespace in my files. I blame this afliction on Terry Hughes. Also surprisingly enough this is the most common JSHint failure that gets me.

One thing that Terry does in Visual Studio is enable visual whitespace so you can see all the nasty mixed tabs/spaces and trailing garbage. I am using Sublime Text 2 as my main editor at the moment, so I went spelunking to figure out how to enable visual whitespace in it.

It turns out to be pretty easy. From the Sublime Text 2 menu, select Preferences> Default - User.

EdTjP

Then add this setting:

{
    "draw_white_space": "all",
    "tab_size": 4,
    "translate_tabs_to_spaces": true
}

The first setting will make whitespace visible at all times. The next two I threw in as a nice suggestion, they will convert tabs to four spaces if you are into that kind of thing. I apparently am also a jerk who will automate cleaning up after you if you don’t care about whitespace. Just this morning I added a plugin to convert tabs to spaces when I save a document. So if I open a file full of horrible tabs, all I have to do is save and it fixed.

Adding the plugin was pretty easy, just select Sublime Text 2 > Preferences > Browse Packages.

EdTjP

Then create a new directory, I called mine “johnson” to avoid conflicts, and create a python script file named tabs_to_spaces.py and add this code to it.

import sublime, sublime_plugin

class ConvertTabsToSpaces(sublime_plugin.EventListener):
    def on_pre_save(self, view):
        edit = view.begin_edit()
        view.run_command('expand_tabs', {"set_translate_tabs": True})
        view.end_edit(edit)

Happy anal text formatting to you!

Why Testing Reality is Always My First Test

16 May 2013

A couple days ago I tweeted a screenshot of a unit test that is usually the first test I write when starting a new project. Regardless of platform the test usually looks something like this.

'use strict';

var assert = require('assert');

exports.test_reality = function(test) {
    test.equals(true, true, 'true should still be true');
    test.done();
};
using NUnit.Framework;

namespace Simple.Data.SqliteTests
{
    [TestFixture]
    public class RealityTests
    {
        [Test]
        public void true_should_be_true()
        {
            Assert.That(true,Is.True);
        }
    }
}

This lead to a couple zany one line zingers on Twitter and Facebook. I even had some one suggest that I was ripping off customers by writing such code.

WE sure do treat our customers like suckers. Let $5000 HTML buttons live on! Aeden Jameson

EdTjP

That little jump to conclusion was pretty surprising. But I moved on and continued working on what I was working on that day. A few days later I got an email from a former colleague.

Sometimes you tweet things (like your boilerplate JS test the other day) that I wish you’d blog about. Go into what inspired that test, why it’s still part of your bootstrap, etc… #creepyrandomemails -JM

So I promised JM that I would blog about the reasons why reality test is the first one I write.

When I am bootstrapping a project, I like to start building out automation from the beginning. With .NET, this is usually a psake based build script. You can see an example from the Simple.Data.Sqlite package I was working on a while back. In node.js, I’ll start with a Jake based script. You can see an example here from a project we created during a node bootcamp.

The goal of this automation is to perform builds, testing, packaging and other types of tasks that developers do on a regular basis in a project in a reapeatable known way. How do you know that the source you have on your local machine is good enough to check in? Run the script, if it passes commit it.

So when I am setting up my basic project structure and automation, I like to have at least one unit test ready to run. This allows me to test the automation script and ensure failures in tests cause failures in builds. In .NET I want to confirm that the compilation step fails properly and the unit tests fail properly. In node.js, I want to ensure that linting errors fail as well as unit tests.

All of this can be done before writing a single line of production code. If you are running a continuous integration server, you can set it up to run your script as well on each check in. How many times have you had a build fail in CI and have no idea why or no way of troubleshooting the issue locally? By having the automation locally and having the CI use that automation, you avoid that problem altogether.

All of this may seem obvious to some folks, but some see it as just a waste of effort. I hope I have explained well enough why I do it for you to at least get the point.

If you want to read up on some of these techniques, I highly recommend the book Growing Object-Oriented Software, Guided by Tests otherwise known as the London School of TDD book.

Growing a API modularly with Node

09 May 2013

This week I started a new gig at Mombo Labs. Lucky for me I finally get to work with some of the technologies I have been interested in for the last year or so as my day job. To get my feet wet and get elbow deep in our codebase, I started exploring our server API by creating a wrapper library for node.js.

EdTjP

Once I got started, I realized that the API has a pretty big surface area dealing with authentication, user CRUD and various domain concepts. I wanted to create a simple entry point for my API but also divide up my code based on domain topic.

I started out creating a constructor for my API that basically sets up some private members and loads up the request module along with some helper functionality around creating endpoint Uris. This code lives in my modules index.js entry point.

'use strict';

var url = require('url');

var Api = exports.Api = function(protocol, host, port, email, password) {
    this.protocol = protocol;
    this.host = host;
    this.port = port;
    this.user_email = email;
    this.user_password = password;
    this.token = '';

    this.request = require('request');

    this.makeUri = function(path) {
        var basePath = 'webexp/';

        return url.format({
            protocol: this.protocol,
            hostname: this.host,
            port: this.port,
            pathname: basePath + path
        });
    };
};

I then wanted to deal with authentication so I created a modules folder next to my index.js and added a authentication.js file. This script basically exports a function that monkey patches an authenticate method on to the scope of the function executor.

'use strict';

module.exports = function(){
    
    this.authenticate = function(email, password, callback) {
        if(typeof email === 'function') callback = email;
        var scope = this;
        var authentication_options = {
            url: this.makeUri('LoginUser'),
            body: JSON.stringify({
                email: this.user_email || email,
                password: this.user_password || password}),
            json: true
        };

        this.request(authentication_options, function(err, res, body){
            scope.token = body.token = res.headers['x-token'];
            callback(err, body);
        });
    };
};

I can now return to my index.js and add a simple require statement like this, to apply my authentication methods to my API object.

require('./modules/authentication').call(Api.prototype);

In case it is not clear, here is a shot of what my project structure looks like.

EdTjP