Website Logo. Upload to /source/logo.png ; disable in /source/_includes/logo.html

A Developer's Blog

Various notes on Web development and tech.

Javascript NaN for New Date Object in IE & Safari

Recently I came across an issue during some cross browser testing of a change I had made which highlighted an interesting issue. It appeared Internet Explorer and Safari seem to handle date strings differently when instantiating new date objects using javascript’s new Date().

The date string I was trying to use to instantiate a new date object looked like the following:

1
'2015-02-16T12:44:42+0000' 

The above format is the basic ISO 8601 notation which includes the timezone offset via the value shown after “+”.

To the best of my knowledge this format is the most widely used across the web but when trying trying to instaniate a new date object like so:

1
var dateTime = new Date('2015-02-16T12:44:42+0000');

This resulted in the NaN message being rendered everywhere I was trying to show a date in IE and Safari but other browsers seemed to handle the string accordingly without any issue.

Following closer inspection of my input datetime string and a few minutes of playing around with my trusty browser console and javascript’s Date(), it turns out the IE and Safari will only accept the the extended date time notation which looks like so:

1
'2015-02-16T12:44:42+00:00'

The difference between the extended notation and the basic notation I had been trying to use was just the inclusion of the colon in the timezone offset value. This left me intrigued as to whether the other browsers which had been working fine with the basic notation would be able to handle the creation of date objects with input strings in extended notation and turns out they could.

Having found out that using the extended notation is always going to be the safer option for cross browser compatibility, I found the solution below to do the trick:

1
2
3
4
var dateTimeString = '2015-02-16T12:44:42+0000';

//add colon to timezone offet
dateTime = dateTimeString.replace(/([+\-]\d\d)(\d\d)$/, "$1:$2");

Should you come across the same issue, hopefully you find this useful.

Qualities of Clean Code: Part1 - Naming of Things

Over the course of the months to come, Im going to be focusing on the topic of clean code and noting all the qualities that constitute clean code through reading and re-factoring code, discussions with fellow developers, and drawing from insight gained through Robert C Martin’s book, Clean Code – A handbook of agile software craftsmenship. As a reminder to myself of the main attributes to always keep in mind and to share with anyone interested in becoming better developers through improving their own code quality; I will be writing a series of posts detailing the main attributes of clean code and their importance.
Firstly, what is the definition of clean code? My interpretation of clean code is code that is:

1.. Simple and easy to understand

2.. Can easily be modified/enhanced by other developers

3.. Testable

To kick off the series of posts, I’m going to start with highlighting the importance of how you name things. Naming is one of the hardest things in software development. Considering how we come to easily understanding some logic is partly hinged on how things were named; it is important we name things properly. By sticking to the following points as rule of thumb we are never going to be far off the mark of attaining clean code.

Be Descriptive

There is nothing more frustrating than realising time spent while trying to work out what some code does through dumping variables or stepping through with debuggers before you can actually make your code change all because of some cryptic class, function and variable names. The names you choose should be able to quickly highlight purpose and shed light on how an item is being used in a particular context. Avoid single letter variable names and ensure that the names you have chosen are pronounceable . Keep in mind that being descriptive doesn’t mean use long names. If the name cannot be noted at a glance then it’s most likely too long. Consider the following piece of code:

1
2
3
4
5
6
7
8
9
10
public function getBlockedItems($dataSet)
{
    $data = [];
    foreach ($dataSet as $key => $value) {
        if ($value['status'] === 'blocked') {
            $data[] = $dataSet[$key];
        }
    }
    return $data;
}

Its not complicated having taken a close at the code to understand what it is doing but there is totally no context to what is going on here. Had things been named in a more descriptive manner you would have clearly understood its purpose in half the time. So how could the code have been written in a clearer more descriptive way?

1
2
3
4
5
6
7
8
9
10
public function getBlockedAccounts($accounts)
{
    $blockedAccounts = [];
    foreach ($accounts as $accountNumber => $accountDetails) {
        if ($accountDetails['status'] === 'blocked') {
            $blockedAccounts[] = $accounts[$accountNumber];
        }
    }
    return $blockedAccounts;
}

With just a few descriptive names, at a glance you can now quickly work out the purpose of the logic and notice what a difference that makes.

Be Consistent

Try be as consistent as possible in your use of the names. Ensure your choice of names for concepts is clearly distinguishable from other procceses. Its confusing to have fetch, get, retrieve littered all over the code in an inconsistent manner. With inconsistency it would make it difficult to quickly work out which function will return data with the attributes you are after.

Avoid abbreviation

Abbreviations are dangerous. Personal interpretation of abbreviations can lead to misunderstanding. You should really avoid using these unless its really unavoidable because extremely long names as mentioned before can also be bad when people are trying to read your code. I would say the only case it might be acceptable is when referring to domain specific phrases.

Avoid Hungarian notation

If still using Hungarian notion you should have stopped a long time ago. Its a dated concept which doesn’t provide any real benefit these days and most of the time is misused. Attempting to use it will most likely only make it harder to understand and follow what your code is doing. To this date a good article still worthwhile reading is Joel Spolsky’s “Making Wrong Code Look Wrong”. His article goes into more detail about the origins of the notation and how the abuse and misunderstanding of it has created issues.

Avoid misleading names

Avoid using names that in the domain of our language choice and field of computer science could mean something else. Using such names could lead to bad assumptions and false conclusion.

Parting words

As general rule of thumb, take time to think about your names and if you need to add comments to explain the purpose of a variable or function internal in your code, you’ve probably already messed up. In that scenario revist your code and reconsider your implementation to see if it can be further simplified in such a way the code expresses itself and the author.

Client Side Dependency Management With Bower

As part of a conquest to improve my general front-end skills, I decided to address the issue of dependency management and decided to familiarise myself with Bower.

Bower is a dependency management solution that helps you overcome the stress of front-end dependency management. It will help you manage your web assets like Javascript, HTML and CSS.

In greater detail and as defined by the Bower team:

Bower is a package manager for the web. It offers a generic, unopinionated solution to the problem of front-end package management, while exposing the package dependency model via an API that can be consumed by a more opinionated build stack. There are no system wide dependencies, no dependencies are shared between different apps, and the dependency tree is flat.

In this post I detail the installation process, issues encountered, how to use it and anything else I found worth remembering.

Getting Started…

Bower has a few dependencies of its own that need to be satisfied before you can use it. To get started ensure you have installed the following:

  1. Node.js
  2. Npm – comes bundled with Node.js installation
  3. Git

Installation

Install Bower globally using npm with -g flag by running the following:

1
$ npm install -g bower

My first attempt of running the above command failed with the following error:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
npm ERR! Error: EACCES, mkdir '/usr/local/lib/node_modules/bower'
npm ERR!  { [Error: EACCES, mkdir '/usr/local/lib/node_modules/bower']
npm ERR!   errno: 3,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/usr/local/lib/node_modules/bower',
npm ERR!   fstream_type: 'Directory',
npm ERR!   fstream_path: '/usr/local/lib/node_modules/bower',
npm ERR!   fstream_class: 'DirWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/dir-writer.js:36:23',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/mkdirp/index.js:37:53',
npm ERR!      'Object.oncomplete (fs.js:107:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

From looking at the error I could tell this was the result of a permissions issue. I attempted to resolve by running the install command as sudo to no avail. If like me, you run into the same issue; you can resolve by changing the ownership of the /usr/local directory to your $USER as follows:

1
$ sudo chown -R $USER /usr/local

After running the above; if you re-run the install command, it should now succeed with no problem. You can now verify that bower has successfully installed by running the following command in your terminal which should then return usage instructions:

1
$ bower

Lets Start Using Bower

Searching For Packages

Locating packages can be done in two ways. You can either find available packages using the component directory or searching using bower’s command line search feature.

For example to search for the popular bootstrap front-end framework, you can simply formulate your command line query like so:

1
$ bower search bootstrap

The query will return a large result set in the format <package_name><git_end_point>. You can use the package name or the git endpoint to install the package.

1
2
3
4
5
6
Search results:

    bootstrap git://github.com/twbs/bootstrap.git
    angular-bootstrap git://github.com/angular-ui/bootstrap-bower.git
    sass-bootstrap git://github.com/jlong/sass-bootstrap.git
    bootstrap-sass git://github.com/jlong/sass-twitter-bootstrap

Installing Packages via Command Line

Having chosen a package to install, you can use the install command with the name of the package you wish to install as the argument.

1
$ bower install <package>

You can also choose to install a specific version of a package by using the hash symbol between the package name and the required version number.

1
$ bower install <package_name>#<version_number>

Installing Packages Using bower.json file

Using the bower.json to install packages provides advantages such as eliminating the need to commit your applications dependencies to version control since all the info will be in the file and will allow you and other project collaborators to easily reproduce an identical software stack.

You can create the file in your application root directory or run bower init command which will generate a template file for you to list your dependencies.

The example below shows a bower.json file which defines some information on the project and a list of its dependencies.

1
2
3
4
5
6
7
8
{
  "name": "sample-app",
  "version": "0.0.1",
  "dependencies": {
    "sass-bootstrap": "~3.0.0",
    "jasmine": "~2.0"
  }
}

Once you have defined all you project dependencies, you can install them all at once by executing the bower install command.

Other useful commands

1
$ bower update

Will update all your dependencies specified in your bower.json file while abiding by the version restrictions you’ve specified.

1
$ bower update <package_name>

Will update the specified package name

1
$ bower uninstall <package_name>

Will uninstall the specified package

Setup Octopress Blog With Github Pages

Having decided to start blogging again after a minor hiatus I’ve decided to start a new blog using Octopress as the framework of choice. It uses Jekyll, the blog aware static site generator that powers Github Pages.

This write up details the process of getting setup and any gotchas I encountered for my own future reference and for anyone that might find this useful.

The setup detailed in this writeup was carried out on my Mac Book Pro, running OS X Mavericks and a zsh terminal.

Prerequisite:

  1. Ensure you have git installed. If you have Xcode tools then you should already have git available on your machine.
  2. Install rvm or rbenv with ruby version 1.9.3. Despite Octopress docs suggesting ruby versions greater than 1.9.3 would suffice, I had issues trying to use v2.0 as some of the Octopress dependencies didnt seem to support it.
  3. Install Bundler, the Ruby dependency manager.

Setup:

Obtain Octopress by cloning it onto your local machine and navigate into the cloned folder.

In my instance I cloned it into a directory called “blog” as follows:

1
2
$ git clone git://github.com/imathis/octopress.git blog
cd blog

Install all the required dependencies:

1
$ bundle install

Install the default Octopress theme:

1
$ rake install

Deployment

For easy publishing and to get free hosting for my blog I decided to use Github pages which also provides me with the domain http://farai.github.io.

To get the hosting setup, log into your Github account and create a github repository with a name in the format of username.github.io where username is your Github user name. Ensure the name of your repository is in the correct format so that Github pages will be able to locate and serve your site as it will serve everything from the master branch of this repo like the web root directory on a server.

As the generated content will be served from the master branch of your repo you will want to work off a separate branch when making changes to your repo. Octopress provides a rake task that helps you setup a good work flow so you can easily manage and deploy:

1
$ rake setup_github_pages

You will notice after running the setup_github_pages task a new branch will have been created for you called “source” and a folder named “deploy”. When making changes to your blog you will now be working off the source branch and every time you perform a deployment, the changes you’ve made will be copied into the deploy folder then pushed upto into the master branch by another set of deployment tasks.

To perform a deployment run the tasks:

1
2
$ rake generate
$ rake deploy

At this stage your site should now be deployed. The pending task would be to ensure you save site changes under source control by committing your changes on the “source” branch as follows:

1
2
3
$ git add .
$ git commit -m 'your desired commit message'
$ git push origin source

Remember to always commit changes made on your source branch.

If you now go ahead and visit http://yourgithubusername.github.io you should now be able to see your live site.

Custom Theme

Upon completion of the setup, I didn’t quite like the default Octopress theme and if you share the same feeling, the following process details how I added a custom theme.

I settled on the Octoflat theme by Alex Garibay and you can choose from a variety of other nice 3rd party Octopress themes.

To install the custom theme I ran the following commands:

1
2
3
4
5
$ cd blog
$ git clone https://github.com/alexgaribay/octoflat .themes/octoflat
$ rake "install[octoflat]"
$ rake generate
$ rake deploy

Note that I quoted the arguments to rake on the install command as opposed to running rake install['octoflat'] as most instructions suggest. This was intentional and due to the fact that instructions found in the docs are Bash oriented and I’m using a Zsh terminal which had me getting the error zsh: no matches found: install[octoflat].

Creating my first post

Octopress also provides a task to help you create your posts preloaded with metadata and according to Jekyll’s naming conventions.

Creating my first post was as easy as running:

1
rake "new_post[Setup Octopress blog with Github Pages]"

And thats all that was to setting up my new Octopress blog.