Chad K. Bibler's Blog

Software engineering for apps in the browser.

Git: show your commits from yesterday

If you have a morning standup meeting or SCRUM like I do, this can save you some time by showing you a quick list of your commit messages from yesterday.

Here’s the command:

git log --oneline --after "`date -v -1d`" --author="`git config --get "user.name"`"

I’ve aliased it to “yesterday” in my shell.

Show useless whitespace in Vim

Here’s a nice little snippet to add to your .vimrc to show unneeded whitespace in your code.

" distilled from http://vim.wikia.com/wiki/Highlight_unwanted_spaces
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
autocmd BufWinEnter * match ExtraWhitespace /\s\+$/
autocmd InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
autocmd InsertLeave * match ExtraWhitespace /\s\+$/ 

I’ve been using it for over a year and it works very well. Now go get rid of some useless bytes!

What software teams must settle early

Style. Us nerds tend to stand out in crowds because of our lack of it. Style, in the sense of fashion, is seemingly subjective and useless. We care about beautiful software, which is why our teams need our own style when it comes to code if we want to have a beautiful codebase.

First and foremost, the team must choose tabs or spaces. This is important because you will be viewing your code using multiple tools: your editor, a debugger, a diffing tool, etc. And each of these tools could handle tabs differently, which makes your code look messy and less readable which will slow you down. If you want my opinion, always use spaces and set your editor to emit n space characters when you press the tab key.

After your team has settled this debate, create a style guide. Google has style guides for a few common languages. These guides don’t have to be canon for your team, but can give you a jumping-off point for creation of your style guide.

If you don’t settle your style rules and enforce them firmly, (here’s a tool that can enforce JavaScript style), then you will have ugly code. It’s true that ugly code can execute and be functionally equivalent, but the best software teams know to write code for humans, not machines.

The earlier you settle these pedantic yet important choices, the faster your team can speed up their iterations and ship!

Git pre-commit hook for linting your CoffeeScripts

A git pre-commit hook is a script that is run every time you run the git commit command. It is used to determine whether or not the commit is allowed to continue. I wanted to run my CoffeeScripts through a linter before they made it into my repository, so I cooked up this script.

This hook depends on the CoffeeLint program being installed, which requires npm.

Create a .git/hooks/pre-commit file and put this script as its contents:

# Pre-commit hook to pass .coffee files through coffeelint

CSLINT="/usr/local/bin/coffeelint"

for file in $(git diff-index --name-only --diff-filter=ACM --cached HEAD -- | grep -P '\.(coffee)$'); do
    echo $file
    $CSLINT $file &> /dev/null
    if [ $? -ne 0 ] ; then
        $CSLINT $file
        exit 1
    else
        exit 0
    fi
done

Then make sure to chmod +x .git/hooks/pre-commit. Also, make sure the pre-commit script is using the right path to your coffeelint executable.

Tip: You can pass –no-verify to git commit to bypass this check.

Sorting an object by value in JavaScript in 2 lines thanks to Underscore.js

Since the ECMAScript standard doesn’t state that keys in an object need to be arranged in a certain order, different JavaScript implementations used by different browsers can behave differently. This means if you need to sort an object by its values, you will need to use a list since list’s orders are guaranteed.

Here’s a tiny (thanks to Underscore.js) function that takes an object of key-value pairs (also known as a hash or map), and returns a list of key-value pairs sorted by ascending value.

function sortByValue(object) {
    var tuples = _.map(object, function (value, key) { return [key, value]; });
    return _.sortBy(tuples, function (tuple) { return tuple[1]; });
}

For example:

var wordOccurrences = {
    "foo": 1,
    "bar": 3,
    "baz": 2
};
sortByValue(wordOccurrences);
// returns [["foo", 1], ["baz", 2], ["bar", 3]]

If you want the sorted values to be descending in value, simply iterate over the returned list backward.

Some JavaScript snipMate snippets

I know I’m wayyy late to the game, but I’ve just started using a vim plugin called snipmate. It allows you to define keystrokes that you type, then press tab, and it will put the contents of the snippet into the file.

Here’s a few JavaScript snippets I’ve been using:

Faster console logging:

snippet con
    console.log( "${1}" );

snippet cons
    console.log( "${1:obj}", ${2:$1} );

And here’s some boilerplate when creating a new “class”:

snippet clas
    var ${1:ClassName} = function() {
        var self = {};
       
        var private_variable = null;
       
        self.public_variable = null;
       
        var init() = function() {
        };
        init();
       
        return self;
    };

And here’s a singleton:

snippet sing
    var ${1:SingletonName} = function() {
        var self = {};
       
        var private_variable = null;
       
        self.public_variable = null;
       
        var init() = function() {
        };
        init();
       
        return self;
    }();

This one saves a lot of typing and looking at documentation for jQuery (version less than 1.6) AJAX calls:

snippet ajax
   $.ajax( {
      type: "${1:POST}",
      dataType: "json",
      url: "${2}",
      data: data,
      success: function( data, textStatus, XHR ) {
      },
      error: function( XHR, textStatus, errorThrown ) {
      },
      complete: function( XHR, textStatus ) { }
   } );

Snipmate is very easy to install and extend. If you’re not using it, you’re wasting time and cycles!

Get a jump start on converting your site to running offline using HTML5 Cache Manifest.

Manifested is a new utility for getting a jump start on converting your existing web site to work offline using HTML5′s cache manifest.

Manifested scrapes a website for images, stylesheets, and JavaScripts that you may want to cache.

Manifested then gives you a custom cache manifest file as a starting point for upgrading your website to support offline functionality.

CoffeeScript HTML5 Cache Manifest Debugging Example

I added the HTML5 cache manifest to Browser Hash today and thought I would share a simple CoffeeScript file to debug and listen to all of the browser’s manifest events.

Introducing Browser Hash

Browser Hash quickly calculates file digests (MD5, SHA-1, SHA-256) in your browser.

There are a lot of advantages for Browser Hash:

  • Privacy. No file contents, names, or digests are sent across the web.
  • Cross platform.
  • Ridiculously easy to use.
  • Free.
  • Sexy.

Unfortunately, there are a few big disadvantages to having your browser do file digests:

  • At the moment, browser support is pretty bad. Only Firefox 3.6+ and Chrome work.
  • The file size limit is artificial, but the supported browsers choke on reading large files.
  • Internet connection required (for now).

What to expect in the future:

  • Offline usage via HTML5′s cache manifest.
  • File size limit removal or bypass by user.
  • A spinoff that optimizes a special use case: Are these files the same?

The Simplest WebWorker in CoffeeScript

Here’s how to do the simplest WebWorker in CoffeeScript.

Here is worker.coffee:

@onmessage = (event) ->
    # event.data holds the call's string
    postMessage "I heard you."

And here’s how you would create the worker, listen to its messages, and pass data to it:

worker = new Worker 'javascripts/worker.js'

# listen for messages from the worker
worker.onmessage = (event) =>
    # event.data holds the data passed FROM the worker
    return

worker.postMessage "Can you hear me?"