Caffeine-Powered Life

Setting Up CouchDB on Ubuntu in Azure

  1. Create a new Ubuntu 14.04 LTS virtual machine.

  2. Add an endpoint for port 5984.

  3. SSH to your newly created machine.

  4. Update your new machine.

     $ sudo apt-get update
    
  5. Install CouchDB.

     $ sudo apt-get install couchdb
    
  6. Ensure that CouchDB is working.

     $ curl -X GET http://localhost:5984
     {"couchdb":"Welcome", "uuid":"80543311a1c6ed1de302adfc970a6d37", "version":"1.5.0", "vendor":{"name":"Ubuntu", "version":"14.04"}}
    
  7. By default CouchDB gets installed and works only on localhost. We will need to edit CouchDB’s configuration file to allow it to work on public ports.

     $ sudo vim /etc/couchdb/default.ini
    

    Find the line that looks like bind_address = 127.0.0.1. Change that to bind_address = 0.0.0.0.

  8. Restart CouchDB.

     $ sudo service couchdb restart
     couchdb stop/waiting
     couchdb start/running, process 1627
    

Happy coding!

Zero Inbox

I’m not joking when I say “zero inbox.” Note, this screen shot lasted for about 3 minutes before another email came in.

You have to work at it each and every day.

The rules are simple. Every time an email comes in, make the following decision.

  1. This email is junk. Delete it.
  2. This email is informational. You read it once and are done with it. Delete it. This includes useful things like, “The build server will be taken offline for two hours tonight so upgrades can be installed.” That’s nice to know. Next, please.
  3. This email is informational and relevant. Add some helpful tags to your email. Do not use folders. Folders only work when only one thing applies. But what if something is both a Receipt and belongs to Client X? It needs two tags. Archive it.
  4. Handle the stuff you can handle the moment it comes in. When you’re done with it, reply, tag it, and move it to Archive.
  5. Anything that you can’t handle gets put into the Follow Up folder. The Follow Up folder is your main work queue. When you done with an item, move it to the Archive.

We all know that you have to make this decision with every piece of mail that you receive. You can either choose to (a) make these decisions one time or (b) make these decisions every time you open your Inbox and start sifting through your mail. If you delay this decision process, then you are just creating a project for yourself when it comes time to find that one important thing.

But Jarrett, I still have too much email!

If you’re doing the above and still have too much email, then here are few other things you need to look into.

  1. Email is not an instant chat client. At Fusion Alliance, we use HipChat. You can create groups and have one-on-one chatrooms. It’s wonderful.
  2. Email in not a file sharing service. But tools like Dropbox, BTSync, OneDrive, Cloud Drive, SharePoint, and many others are, in fact, file sharing services. Create a folder to share with your clients, project team, or whatever, and put all common documents there. Also, your network administrators will thank you for getting rid of all those giant attachments.
  3. Use those Unsubscribe links. Find yourself deleting the same junk over and over again? Maybe take steps to slow the junk.
  4. Use mail rules to your advantage. This can be especially helpful with automatically adding those tags that we discussed earlier or deleting stuff that you know is garbage.
  5. Quit it! If you are drowning in email, then you are probably one of the most unproductive, unreliable, unprepared employees at your job. If you say, “I have too much email to deal with,” then someone like me hears, “I spend all my time switching context and jumping from one fire to the next.” Seriously, this warrants a discussion with the appropriate parties. No one can be effective under that kind of stress. Sometimes, you’ve got to stand up for you!

I can do it, and so can you!

Angular Part 5: Testing

Today is Halloween in the United States. As such, I think we should talk about something scary.

No, not lions and tigers and bears. Something that drives fear into the hearts of developers: unit testing.

Seriously, this is not that difficult. Part of learning any new programming language or framework includes learning how to test that language or framework. This is 2014. If automated unit and integration testing isn’t a first-level design concern by now, you are doing it wrong. (I’m looking at you Microsoft WebAPI.)

Angular makes writing unit tests incredibly easy. JavaScript is fragile enough as-is, so let’s always test all of our *.js files. Quasi-futuristic languages like TypeScript or AtScript might offer us runtime type checking, but that is still runtime checking. That means to thoroughly test your application, you must run through all possible code routes.

The tools

This is the list of tools we will be using for this project.

The application (app.js)

The application is very easy to define and test.

First we declare it.

app/app.js
1
angular.module("myApp", []);

Then we make sure we can get it.

spec/appSpec.js
1
2
3
4
5
6
7
describe("module: myApp", function () {

  it("is defined", function () {
    expect(angular.module("myApp")).toBeDefined();
  });

});

The point service (point.js)

The point service is taken from our previous post. It looked like this.

app/services/point.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
app.factory("point", [
  function () {
    return function (options) {

      options = options || {};

      var self = {
        x: options.x || 0,
        y: options.y || 0
      };

      self.distanceTo = function (other) {
        var absXSq = sqError(self.x, other.x);
        var absYSq = sqError(self.y, other.y);
        return Math.sqrt(absXSq + absYSq);
      };

      self.toString = function () {
        return "Point: { " + self.x + ", " + self.y + " }";
      };

      function sqError(a, b) {
        return Math.pow(a - b, 2);
      }

      return self;
    };
  }
]);

The unit test below defines what our point service should be able to do.

spec/services/pointSpec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
describe("service: point", function () {

  var point;

  beforeEach(module("myApp"));

  beforeEach(inject(function (_point_) {
    point = _point_;
  }));

  it("can create a new point object representing the origin", function () {
    var pt = point()
    expect(pt.x).toEqual(0);
    expect(pt.y).toEqual(0);
  });

  it("can calculate the distance between two points", function () {
    var origin = point();
    var pt = point({ x: 3, y: 4 });
    expect(pt.distanceTo(origin)).toEqual(5);
  });

  it("returns the expected value for toString()", function () {
    expect(point({ x: 1, y: 2 }).toString()).toEqual("Point: { 1, 2 }");
  });

});

The parts to notice are the two beforeEach() functions. The first one loads the module. The second one sets up the service to be tested. The _point_ is used by the injector to create the point instance.

Yes, it’s a bit magical how the injector works. Basically, any inject() argument that starts with $ is an Angular built-in, and any argument that looks like _something_ is something you’ve written. Beyond the injection magic, the tests are rather straightforward. We can create a new point, calculate the distance between two points, and test its string representation.

The controller (PointCtrl.js)

Our PointCtrl is quite small, especially since most of the work is being handled by the point service. That was why we wrote the service in the first place.

app/controllers/PointCtrl.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
app.controller("PointCtrl", [
  "$scope",
  "point",
  function ($scope, point) {

    $scope.point1 = point();
    $scope.point2 = point();

    $scope.getDistance = function() {
      return $scope.point1.distanceTo($scope.point2);
    };

    return $scope;
  }
]);

The test for the controller is similarly simple, once you figure out the test setup steps.

spec/controllers/PointCtrlSpec.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
describe("controller: PointCtrl", function () {

  var ctrl, distance, point, scope;

  beforeEach(module("myApp"));

  beforeEach(inject(function ($controller) {
    createMockPoint();
    createController($controller);
  }));

  it("assigns point1 and point2", function () {
    expect(scope.point1).toBeDefined();
    expect(scope.point2).toBeDefined();
  });

  it("returns the expected value for getDistance()", function () {
    expect(scope.getDistance()).toEqual(distance);
  });

  function createController($controller) {
    scope = {};
    ctrl = $controller("PointCtrl", {
      "$scope": scope,
      "point": point
    });
  }

  function createMockPoint() {
    distance = Math.random() * 100;
    point = function () {
      return {
        distanceTo: function () {
          return distance;
        }
      };
    };
  }

});

Again, the trick to these tests is understanding the beforeEach() functions. The first one loads the module. The second loads the $controller factory.

You will notice that we create a mock point object and a mock $scope object. I have discussed mocking JavaScript objects before, and I follow the same pattern here. Since there is no type system in JavaScript, we only care that the object we create has the same functions and properties as what we use.

How much of a mock do you need? You need as much of the object surface area as the controller has access. For $scope, an object literal ({}) will do, and there is no reason for anything more complicated than this.

The point object is a little more complicated. First, it needs to be a function, so we can call point(). Second, the controller needs access to the distanceTo() function. We will create a stub for this function and return a random value between 0 and 100.

The final result

Running all of tests in the browser, we should see the following.

The complete series

Angular Part 4: Creating a Service

Our last project covered dependency injection in an Angular application. Now, let’s show how a service works.

An Angular service is a way to encapsulate business logic so that it can be consumed by controllers and other services. Like any well-written program, functionality that goes together should be put together in small, reusable, testable components. Speaking of testing, that’s going to be the next post, so stay tuned.

Demonstration of application

The application should work similar to the following example.

Our new service

We will encapsulate the point object into an Angular service. This service will be called “point”, and it will have no dependencies. You will notice that this block of code looks almost identical to the point() function from our previous post.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
angular.module("myApp").factory("point", [
  function () {
    return function (options) {
      var self = {
        x: options.x,
        y: options.y
      };
      self.distanceTo = function (other) {
        var absXSq = sqError(self.x, other.x);
        var absYSq = sqError(self.y, other.y);
        return Math.sqrt(absXSq + absYSq);
      };
      self.toString = function () {
        return "{ " + self.x + ", " + self.y + " }";
      };
      function sqError(a, b) {
        return Math.pow(a - b, 2);
      }
      return self;
    };
  }
]);

By giving our service a unique name, we can now inject it into our controllers as needed.

1
2
3
4
5
6
7
8
9
10
11
12
angular.module("myApp").controller("PointCtrl", [
  "$scope",
  "point",
  function ($scope, point) {
    $scope.point1 = point({ x: 0, y: 0 });
    $scope.point2 = point({ x: 0, y: 0 });
    $scope.getDistance = function () {
      return $scope.point1.distanceTo($scope.point2);
    };
    return $scope;
  }
]);

Adding a service makes our controller much simpler than the previous post. Additionally, our point is now a focused, reusable block of code that can be used anywhere within our application.

It is important to note that all Angular services are lazy singletons. Specifically, they are only created when asked for, and only one instance of the function will ever be created. This is great for your application’s memory profile.

The complete series

Angular Part 3: Dependency Injection

In my previous post, I showed how a controller is built in Angular. The basic syntax for creating a controller looks like the following.

1
2
3
4
5
6
module.controller("MyCtrl", [
  "$scope",
  function ($scope) {
    return $scope;
  }
]);

This syntax for creating a JavaScript module is incredibly powerful. By letting Angular handle all of the dependencies, and by treating the scope as yet another object to be injected, the developer needn’t ever worry about three of the most difficult concepts in JavaScript: specifically, closures, new, and this.

The Traditional JavaScript Object

For a refresher, here’s the traditional way to create an object in JavaScript.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var Point = (function () {

  function Point(options) {
    this.x = options.x;
    this.y = options.y;
  }

  Point.prototype.distanceTo = function (otherPoint) {
    var absXSq = Math.pow(this.x - otherPoint.x, 2);
    var absYSq = Math.pow(this.y - otherPoint.y, 2);
    return Math.sqrt(absXSq + absYSq);
  };

  return Point;

})();

We create a new point in the following manner.

1
var origin = new Point({ x: 0, y: 0 });

In the above class, this is always the functional enclosure that defines the class. This means that this acts the same as we would expect it in C# or Java. However, it wouldn’t take much, just a simple callback, to change the result. Imagine a more complex function that needs to be non-blocking.

1
2
3
4
5
6
7
Point.prototype.distanceTo = function (otherPoint) {
  return setTimeout(function () {
    // Here, any reference to this.x or this.y will cause your
    // program to fail. Inside the setTimeout callback, this
    // refers to the global scope.
  }, 0);
};

Yes, there are ways to get around the above, specifically by learning how bind(this) works, but, in my experience, this is a place where many developers tend to not know what they are doing. Unfortunately, too many JavaScript “developers” are frequently C# or Java developers who have been asked to add functionality to a web site. They then write mediocre, fragile JavaScript.

An Alternate JavaScript Object

Instead, let’s examine an alternate way to writing our Point class. In this example, we are creating an object literal and attaching functions to this new object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function point(options) {

  self = {
    x: options.x,
    y: options.y
  };

  self.distanceTo = function (otherPoint) {
    var absXSq = Math.pow(self.x - otherPoint.x, 2);
    var absYSq = Math.pow(self.y - otherPoint.y, 2);
    return Math.sqrt(absXSq + absYSq);
  };

  return self;
}

No longer do we have to worry about immediate functions, the (function () {})() syntax, this, or even creating a new object. To create a new point in this manner, we simply do the following.

1
var origin = point({ x: 0, y: 0 });

Angular Objects

Angular gets around of all of this (Ha! Ha! Puns!) by injecting the scope object. Anything you wish to expose gets attached to the scope object. Also, the developer never needs to create new objects. The Angular framework does all of that work for you.

Let’s create a simple form for displaying the distance between two points.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<body ng-app="myApp">

  <div ng-controller="PointCtrl">
    <p>
      <label>x1</label>
      <input type="number" ng-model="x1"/>
      <label>y1</label>
      <input type="number" ng-model="y1"/>
    </p>
    <p>
      <label>x2</label>
      <input type="number" ng-model="x2"/>
      <label>y2</label>
      <input type="number" ng-model="y2"/>
    </p>
    <p>
      <label>Distance</label>
      <span ng-bind="getDistance()"></span>
    </p>
  </div>

</body>

Our controller will look something like the following.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
angular.module("myApp").controller("PointCtrl", [
  "$scope",
  function ($scope) {

    $scope.x1 = 0;
    $scope.x2 = 0;
    $scope.y1 = 0;
    $scope.y2 = 0;

    function squareError(a, b) {
      return Math.pow(a - b, 2);
    }

    $scope.getDistance = function () {
      var absXSq = squareError($scope.x1, $scope.x2);
      var absYSq = squareError($scope.y1, $scope.y2);
      return Math.sqrt(absXSq + absYSq);
    };

    return $scope;
  }
]);

Together, the above HTML and JavaScript should give us something like this.

As mentioned previously, anything that gets attached to $scope is publicly accessible. The squareError() function is not available publicly. There is no binding trick that the developer can use to attach the function to any Angular directive.

Finally, let’s look at the format of the controller definition.

1
module.controller(String, Array);

The String is the name of the controller. The Array is the names of the dependencies with the last element of the array being the definition of the controller. Dependencies that start with a $ are built-ins for Angular — there are several.

Conclusion

I recently watched Douglas Crockford talk about writing JavaScript without using new or this. At first I was quite taken aback. How the hell am I supposed to write JS without objects? As you can see, we can still create plenty of objects, those objects have attributes, attach functions to those objects, and even have private function encapsulation without ever using new or this.

The complete series

Angular Part 2: Moving to a Controller

In Part 1, we showed how easy it is to add functionality to a website with AngularJS, and compared that to how much work would be necessary to do the same thing using jQuery alone.

We did have a little bit of logic in our views, though, and that’s not ideal. That logic was testing for specific values for our form fields.

1
2
3
4
5
// Showing the form field
ng-show="favoriteColor === 'Other'"

// Requiring the form field
ng-require="favoriteColor === 'Other'"

In my opinion, even something as simple as a test for equality is view logic, and we should do what we can to move that out of the view. Ideally, we want something that looks more like this.

1
2
3
4
5
// Showing the form field
ng-show="showOtherField()"

// Requiring the form field
ng-require="requireOtherField()"

Moving that logic is not difficult. In Angular, this kind of thing is handled by the controller.

Before we can write a controller, we first need a module. Defining a module takes the signature angular.module(String, Array). The string is the name of the module, and the array is the list of dependencies required by the module. Below, we define a module named myApp, followed by an array of dependencies. In this case, we do not have any dependencies, so we just have an empty array.

1
2
3
4
if (window.app) {
  throw Error("window.app is already defined.");
}
window.app = angular.module("myApp", []);

Now that we’ve defined our module, let’s define our controller. We get our module from the Angular registry and add a controller to it. Defining a controller takes the signature module.controller(String, Array).

The array is the list of dependencies followed by the definition of the controller. Our controller does have a $scope dependencies. $scope is Angular’s way of not having to deal with JavaScript’s this object. Anything that we want to expose, we add to the $scope object.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
angular.module("myApp")
.controller("ColorFormCtrl", [
  "$scope",
  function ($scope) {

    /**
     * Return true if the submit button should be disabled.
     */
    $scope.disableSubmit = function () {
      return $scope.form.$pristine || $scope.form.$invalid;
    };

    /**
     * Return true if the "Other" field is required.
     */
    $scope.requireOtherField = function () {
      return $scope.favoriteColor === "Other";
    };

    /**
     * Return true if the "Other" field should be displayed.
     */
    $scope.showOtherField = function () {
      return $scope.favoriteColor === "Other";
    };

    return $scope;
  }
]);

Let’s take look at updated HTML.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<html ng-app="myApp">
<head lang="en">
  <meta charset="UTF-8">
  <title>Angular Demo</title>
</head>
<body ng-controller="ColorFormCtrl">
<form method="post" action="#" name="form">
  <div>
    <label>What is your favorite color?</label>
    <select name="favoriteColor" ng-model="favoriteColor" required="required">
      <option></option>
      <option>Red</option>
      <option>Blue</option>
      <option>Other</option>
    </select>
  </div>
  <div ng-show="showOtherField()">
    <label>Favorite color (other)</label>
    <input type="text" name="favoriteColorOther" ng-model="favoriteColorOther" ng-required="requireOtherField()"/>
  </div>
  <div>
    <button type="submit" ng-disabled="disableSubmit()">
      Submit
    </button>
  </div>
</form>
</body>
</html>

We added our module’s name to the ng-app="myApp" directive. We added our controller as part of the ng-controller="ColorFormCtrl" directive. We then moved all of our page logic to a controller.

The complete series

Angular Part 1: Show and Hide

This week, I have been diving headfirst into AngularJS. I am amazed at how much one can accomplish with very little code. In this example, I want to show and hide various parts of a form based on what selections the user makes elsewhere. That’s a pretty simple thing to do with jQuery. It’s even easier with AngularJS.

First, let’s show our base markup. This is the bare minimum to get our page to work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<html>
<head>
  <title>Angular Demo</title>
</head>
<body>
  <form method="post" action="#">
    <div>
      <label>What is your favorite color?</label>
      <select name="favoriteColor">
        <option></option>
        <option>Red</option>
        <option>Blue</option>
        <option>Other</option>
      </select>
    </div>
    <div>
      <label>Favorite color (other)</label>
      <input type="text" name="favoriteColorOther"/>
    </div>
    <div>
      <button type="submit">
        Submit
      </button>
    </div>
  </form>
</body>
</html>

The above HTML will render as follows.

"Angular 1-1"

If we already know jQuery, we know that we need to add a little more to our markup to make it play nice with jQuery.

  1. Add an ID to our select box.
  2. Add an ID to our wrapper div tag for our “Other” input.
  3. Hide the “Other” form field by default.
  4. Write a little bit of jQuery.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!-- Update select -->
<select name="favoriteColor" id="favoriteColor">

<!-- Update div, add inline style -->
<div id="form-field-favoriteColorOther" style="display: none;">

<!-- Write a little script -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
  $("#favoriteColor").on("change", function () {
    if ($("#favoriteColor").val() === "Other") {
      $("#form-field-favoriteColorOther").show();
    } else {
      $("#form-field-favoriteColorOther").hide();
    }
  });
</script>

That’s really not too bad. Let’s however, add a few more requirements.

  1. The Favorite Color option needs to be required.
  2. The Other field needs to be required if Other is selected.
  3. Don’t let the user submit an invalid form.

HTML 5 gives us some of this, but we still run into walls. We’re going to have to add a disabled attribute to the button. We’re going to have to validate our form with another library (or roll our own). We need to add required to the select box. We need to add required to our text box, but only if “Other” is selected.

The program flow should look like this.

This is the default state of the form.

"Angular 1-2a"

User selects an option that is not “Other”. Everything is good. Enable the submit button.

"Angular 1-2b"

User select “Other”. Show a text box and disable the submit button.

"Angular 1-2c"

User enters a value in the text box. Everything is good again. Enable the submit button.

"Angular 1-2d"

Again, none of this is particularly difficult, but you can imagine how all of this blows up when a page gets to be of a certain complexity. Let’s see what AngularJS has to offer.

  1. Add ng-model tags to the form fields that we need to expose to angular. That’s both of them.
  2. Add ng-required to any field that is dynamically required.
  3. Add ng-disabled to any field that is dynamically disabled.
  4. Wire it all together.

Let’s look at our AngularJS markup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html>
<head lang="en">
  <meta charset="UTF-8">
  <title>Angular Demo</title>
</head>
<body ng-app="">
  <form method="post" action="#" name="form">
    <div>
      <label>What is your favorite color?</label>
      <select name="favoriteColor" ng-model="favoriteColor" required>
        <option></option>
        <option>Red</option>
        <option>Blue</option>
        <option>Other</option>
      </select>
    </div>
    <div ng-show="favoriteColor === 'Other'">
      <label>Favorite color (other)</label>
      <input type="text" name="favoriteColorOther" ng-model="favoriteColorOther" ng-required="favoriteColor === 'Other'"/>
    </div>
    <div>
      <button type="submit" ng-disabled="form.$invalid">
        Submit
      </button>
    </div>
  </form>
</body>
</html>

Let’s compare our jQuery markup with our AngularJS markup.

  1. The body tag now has an ng-app="" attribute. This is what tells Angular that it should work.
  2. We have added a name="form" attribute to our form. By giving the form a name, it can be accessed by Angular. This access can be seen on the submit button, with the form.$invalid variable.
  3. We have added ng-model="..." to both of our input fields. This exposes the form fields to Angular.
  4. We have added a required HTML5 attribute to our select.
  5. We have added ng-show="favoriteColor === 'Other'" to our div tag that wraps our text box. This means that the field will only be shown if the expression is truthy.
  6. We added an ng-required attribute to our text box. This means the field will be required if the expression is truthy.
  7. Finally, we added an ng-disabled attribute to our button. This means that the button will be disabled if the expression is truthy.

Now, let’s show the JavaScript we need to write to make all this magic happen.

1
// Boo!

Yep. We’re done. Zero lines of JavaScript. Yeah, I could get used to this.

The complete series

Oops! How to Permanently Delete a File From Git

I accidentally added an uninitialized (appended) SQL Server backup file, a *.bak, to source control and pushed it. Now, no one can fetch a clean copy of the source because of out-of-memory errors. How do I fix this?

1
git filter-branch --tree-filter 'git rm -r -f --ignore-unmatch *.bak' HEAD

This will take a while to run, as it goes through every commit in your project and deletes the file. When you’re done, you’ll need to push the file to your remote.

1
git push origin master --force

You’ll need the --force flag because this is not a fast-forward commit.

Getting Started With MathJax

I’ve spent the past few days getting myself reacquainted with TeX and familiarizing myself with MathJax. As it turns out, it is quite easy to get MathJax working in Octopress.

  1. Open source/_includes/custom/head.html.
  2. Add the a JavaScript source: //cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_HTMLorMML.
  3. Start typing your TeX.
  4. In your Gemfile, make sure you are using at least RDiscount version 2.1. gem 'rdiscount', '~> 2.1'
  5. In your _config.yml file, disable automatic superscripts by adding - no_superscript to your RDiscount configuration.

The last two are quite important. Without those two steps, it looks like RDiscount will turn x^2 into x<sup>2</sup>. This will get displayed as x2. That will break the MathJax processor.

Let’s start by demonstrating a simple inline equation, like \( y = mx + c \). This is simple enough by including the inline text: \\( y = mx + c \\).

To enter full equations, like the one below, use the following syntax.

1
2
3
\begin{equation}
x = \dfrac{ -b \pm \sqrt{ b^2 - 4ac } }{ 2a }
\end{equation}

The above code will render as the following equation.

\begin{equation} x = \dfrac{ -b \pm \sqrt{ b^2 - 4ac } }{ 2a } \end{equation}

Happy mathing!

Mocking a JavaScript Constructor

"You're mocking me, aren't you?"

JavaScript, and dynamic languages in general, make it extremely easy to mock out functions. This greatly reduces the need for all the extra programming junk (interfaces, adapters, wrappers, factories, etc.) that gets in the way of us solving our problems. We add tons of extra layers in the name of test isolation and object independence that plainly isn’t necessary in the dynamic languages world.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// lib/Point.js
var Point = (function () {

  function Point(x, y) {
    this.x = x;
    this.y = y;
  }

  Point.prototype.distanceTo = function(point) {
    var dx = this.x - point.x;
    var dy = this.y - point.y;
    return Math.sqrt(dx * dx + dy * dy);
  };

  Point.origin = function () {
    return new Point(0, 0);
  };

  return Point;

}).call(this);

module.exports = Point;

We’ve defined a very simple class, and it has all of the parts that we need to demonstrate how mocking works.

First, let’s define some simple tests. I’m using Jasmine and Node. (See jasmine-node for a command line version of Jasmine.) These tests fully describe the basic functionality of the class.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// spec/PointSpec.js
var Point = require("../lib/Point");

describe("Point", function () {

  var point;

  beforeEach(function () {
    point = new Point(3, 4);
  });

  it("can return the distance to the origin", function () {
    var distance = point.distanceTo(Point.origin());
    expect(distance).toEqual(5);
  });

  it("returns the expected value when constructing an origin", function () {
    var origin = Point.origin();
    expect(origin.x).toEqual(0);
    expect(origin.y).toEqual(0);
  });

  it("returns the expected values for x and y", function () {
    expect(point.x).toEqual(3);
    expect(point.y).toEqual(4);
  });

});

Mocking an instance function.

The distanceTo() function exists on the instance of Point. It’s incredibly easy to mock out. Functions are first-class members in JavaScript, so we can simply redefine the function in the unit test. In this example, we simply redefine the function to return 0.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
describe("Point with stubbed distanceTo() function", function () {

  var point;

  beforeEach(function() {
    point = new Point(3, 4);
    point.distanceTo = function (point) {
      return 0;
    };
  });

  it("returns 0 via stub", function () {
    var distance = point.distanceTo(new Point(10, 10));
    expect(distance).toEqual(0);
  });

});

Mocking a class function.

The origin() function is a class function that returns the point {0, 0}. Let’s suppose we need to define a different origin. That’s easy to do!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
describe("Point with stubbed origin() function", function () {

  var point, temp;

  beforeEach(function () {
    temp = Point.origin; // Save the definition for later.
    Point.origin = function () {
      return new Point(1, 1);
    };
    point = Point.origin();
  });

  afterEach(function () {
    Point.origin = temp; // Restore the original definition.
  });

  it("has the expected values for x and y", function () {
    expect(point.x).toEqual(1);
    expect(point.y).toEqual(1);
  });

});

In this case, we need to store the original definition of origin() in the temp variable. In beforeEach(), we will override the origin() function. In afterEach(), we will restore it to its former glory.

Mocking the class constructor.

Of the three, mocking the constructor takes a little more insight, but the activity is functionally the same. We are going to create a new class and copy all of the necessary functionality to the new class. We do this by copying over the prototype of the original point. We also need to explicitly copy over the origin() function, since class functions are not part of the prototype.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
describe("Point with stubbed constructor", function () {

  var MockPoint = (function () {
    function MockPoint(x, y) {
      this.x = 0;
      this.y = 0;
    }
    return MockPoint;
  }).call(this);

  // Apply all functions from Point to MockPoint. Also copy the
  // origin() function to MockPoint.
  MockPoint.prototype = Point.prototype;
  MockPoint.origin = Point.origin;

  var point, temp;

  beforeEach(function () {
    temp = Point; // Save the definition for later.
    Point = MockPoint;
  });

  afterEach(function () {
    Point = temp; // Restore the original definition.
  });

  it("calculates distance correctly", function () {
    var distance = new Point(3, 4).distanceTo(new Point(6, 7));
    expect(distance).toEqual(0);
  });

  it("can stub out the constructor", function () {
    point = new Point(4, 5);
    expect(point.x).toEqual(0);
    expect(point.y).toEqual(0);
  });

  it("leaves the origin() function unchanged", function () {
    point = Point.origin();
    expect(point.x).toEqual(0);
    expect(point.y).toEqual(0);
  });

});

The pattern is the same. Create a copy. Redefine the function. (The constructor is just another function, just treated a little differently.) Do your tests. Restore the original definition.

I hope this clears up some of the issues around mocking JavaScript objects. This can be done easily with the language and require no additional 3rd party libraries.