Have you ever seen this in your code?

var thingy = require('../../../../thingy.js');

There are lots of “solutions” to this problem. There is even a gist outlining seven of them. To be frank, all seven of them have issues. I’ve spent a stupid amount of time trying to solve this problem. I wanted a solution where I could simply require a module that would return a string of the absolute path to the base of my project. That way you could simply do:

var __base = require('__base');
var thingy = require(__base + 'lib/thingy.js');

Originally I built the project-base npm package that worked. The problem is that it relies on the fact that npm installs your modules into the node_modules directory that lives directly below the base of your project. Recently npm optimized its dependency algorithm to flatten the dependency tree for duplicate modules. That broke the underlying assumption of project-base.

All that to say, I found a work around. Add the following postinstall to the scripts section of your package.json:

{
  ...
  "scripts": {
    ...
    "postinstall": "mkdir -p ./node_modules/__base && echo \"module.exports = require('path').resolve(__dirname + '/../../') + '/';\" > ./node_modules/__base/index.js"
  },
}

This will create a file in node_modules/__base that does exactly what you would expect, returns the absolute path to the base of your project. Problem solved!

Feel free to reach out to me on twitter @jondelamotte.

Diagrams. Everyone loves them, and I hate to make them. That changed recently when I discovered a nifty tool called graphviz. Think of it like markdown for diagrams. It’s an old command line binary tool that basically acts as a compiler for your graph code. We’re talking old school here. The docs are hard to read, the website looks like it was made in the 90s, and there are very few examples on the web that I could find. But once I waded through the initial learning curve, I found a hidden gem.

From what I’ve learned, graphviz has lots of features and can render a ton of different formats. The one that I found actually useful is the “DOT language”. DOT is a mini-language for describing how your diagrams should look. You run your .dot files through graphviz and out comes some pretty graphs in png, svg, you name it. You simply declare all the “nodes” and their relationships, and let graphviz take care of drawing and lining everything up. It’s freeing to not have to spend time fiddling with the layout and spend more time thinking about the components and their relationships.

Installation

These instructions are for people with Macs and homebrew. It’s probably a similar process for Linux. All you need to do is install the graphviz homebrew package. This will make available a suite of command line tools. We’re interested in dot.

brew install graphviz

Learn by example

There are two main types of graphs I have explored so far: digraph and graph. The first is for graphs that have pointy arrows to connect nodes, and the other is for direction agnostic connection. This should make sense once you see a few examples.

To make a new graph, simply save a text file with the extension .dot. You don’t technically need the extension, but it helps keep things orderly. To render the graph to svg (my personal favorite format) use a command like this:

dot -o myfile.svg myfile.dot -Tsvg

Rather than explain all the details of the dot language. Let’s take a look at a bunch of examples and leave it to your fine brain to work out the rest. Look below each diagram for their corresponding DOT code.

Basics

something

graph my_graph {
  joe   [label = "Joe"];
  sally [label = "Sally"];
  frank [label = "Frank"];
  susan [label = "Susan"];
}

something

graph my_graph {
  node  [shape = box];

  joe   [label = "Joe"];
  sally [label = "Sally"];
  frank [label = "Frank"];
  susan [label = "Susan"];
}

something

graph my_graph {
  joe   [label = "Joe", shape = box];
  sally [label = "Sally"];
  frank [label = "Frank"];
  susan [label = "Susan"];
}

something

graph my_graph {
  joe   [label = "Joe"];
  sally [label = "Sally"];
  frank [label = "Frank"];
  susan [label = "Susan"];

  joe   -- sally;
  joe   -- frank;
  frank -- susan;
  sally -- frank;
  sally -- susan;
}

something

graph my_graph {
  joe   [label = "Joe"];
  sally [label = "Sally"];
  frank [label = "Frank"];
  susan [label = "Susan"];

  joe   -- sally;
  joe   -- frank [label = "strong dislike"];
  frank -- susan;
  sally -- frank;
  sally -- susan;
}

something

digraph my_graph {
  joe   [label = "Joe"];
  sally [label = "Sally"];
  frank [label = "Frank"];
  susan [label = "Susan"];

  joe   -> sally;
  joe   -> frank;
  frank -> susan;
  sally -> frank;
  sally -> susan;
}

something

digraph my_graph {
  rankdir = LR; // alternatively TB, BT, or RL

  joe   [label = "Joe"];
  sally [label = "Sally"];
  frank [label = "Frank"];
  susan [label = "Susan"];

  joe   -> sally;
  joe   -> frank;
  frank -> susan;
  sally -> frank;
  sally -> susan;
}

Clusters

something

digraph my_graph {
  rankdir = LR;

  // the "cluster" prefix is required
  subgraph cluster_boys {
    joe   [label = "Joe"];
    frank [label = "Frank"];
  }

  // the "cluster" prefix is required
  subgraph cluster_girls {
    sally [label = "Sally"];
    susan [label = "Susan"];
  }

  joe   -> sally;
  joe   -> frank;
  frank -> susan;
  sally -> frank;
  sally -> susan;
}

something

digraph my_graph {
  rankdir = LR;

  // the "cluster" prefix is required
  subgraph cluster_boys {
    label = "Boys";

    joe   [label = "Joe"];
    frank [label = "Frank"];
  }

  // the "cluster" prefix is required
  subgraph cluster_girls {
    label = "Girls";
    labeljust = right;

    sally [label = "Sally"];
    susan [label = "Susan"];
  }

  joe   -> sally;
  joe   -> frank;
  frank -> susan;
  sally -> frank;
  sally -> susan;
}

Records

something

digraph my_graph {
  node [shape = record];
  rankdir = LR;

  people [label = "<people> people | <id> id | <name> name | <car_id> car_id"]
  cars   [label = "<cars> cars | <id> id"]
}

something

digraph my_graph {
  node [shape = record];
  rankdir = LR;

  people [label = "<people> people | <id> id | <name> name | <car_id> car_id"]
  cars   [label = "<cars> cars | <id> id"]

  people:car_id -> cars:id;
}

Further reading

I may update this post in the future as I learn more about graphiz. Here are a couple links I’ve found useful:

Feel free to reach out to me on twitter @jondelamotte

“Perfecting oneself is as much unlearning as it is learning.” - Edsger Dijkstra

Functional programming is all the rage these days. It’s hard to go to a conference, the water cooler, or your grandmas house without hearing about it. To initiates it’s an insurmountable wall containing droves of intellectual giants and the answers to all your bugs. To learners it’s the great mind twist that forces them to revisit and rethink many of the premises on which they learned the craft. Beyond that stage I can only surmise. Is programming nirvana really found in functional programming? I honestly don’t know yet, but I’m making 2015 the year I find out.

In school I learned object oriented programming in languages like Java and C#. Once I joined the work force, I landed a job that demanded SQL chops almost exclusively. SQL quickly became a gateway drug back into real programming and that’s when I relearned JavaScript. JavaScript was one of the best decisions I made early in my career. Not because it’s a particularly elegant language, but because it’s a melting pot of ideas.

In JavaScript you’re constantly bombarded with new approaches, libraries, and frameworks. There is a certain stamina needed to keep your sanity. The moment you find yourself comfortable with something, it gets replaced with something better (sometimes). For many, that is the primary complaint about web programming. For me, and many of the people I’ve worked with, it’s what gets us up in the morning. There is an underlying attitude that is frequently willing to approach problems from new angles, a constant quest for perfection.

JavaScript helped introduce me to lots of the fundamental concepts of functional programming. While JavaScript can be written in a very functional style, it’s still a very imperative language. To get around this issue people have written lots of libraries that help you write in a more functional style. My plan for this year is pretty simple:

  1. Learn Haskell
  2. Build two trivial command line applications in Haskell
  3. Use functional techniques and libraries to improve my company’s web application

I am focussing on Haskell because I constantly hear it referred to as the model functional programming language. So much of the language doesn’t compromise and forces you to learn the truly functional approach. I want to fully embrace the paradigm shift and Haskell will beat me over the head until I do.

Let’s be real here. There’s not enough time for me this year to get beyond writing trivial applications in Haskell. So, I’m setting the bar pretty low by trying to write a couple relatively simple command line applications.

My last goal integrates best with my day job. One of the challenges with the web application I work on is its rampant state mutation. The biggest offender is the DOM. People modify DOM willy nilly jQuery style and it makes our application incredibly complex. My goal is to find out if a less state based approach will improve the maintenance of our application. I dearly want to put a debugger statement in one place and observe everything that is modifying the DOM.

The end goal is to make my life easier. I want to make it easier to maintain the applications I build. I have a strong feeling that functional is going to make that happen. I don’t think it’s the silver bullet, but perhaps its better than object oriented. Stay tuned for more updates on how this year’s goals are going. Most of my posts this year will be related to JavaScript.

Feel free to reach out to me on twitter @jondelamotte.

One of the challenges of working with Git, or any source control for that matter, is managing branches. The GitHub network graph helps you visualize branches and how they fit together. I wrote a little command to open the webpage from your command line. Note: this only works on Mac, though it could easily be tweaked to work on linux.

Network graph

Put the following line in your .bashrc or .zshrc:

alias gn="git remote -v | grep 'git@github' | sed 's/origin.*:\([^.]*\).*/\1/' | head -n1 | read GH; /usr/bin/open -a \"/Applications/Google Chrome.app\" \"https://github.com/\$GH/network\""

Type gn from the root directory of your git project and it will open the GitHub network page inside of chrome.

This post was created primarily for me, and secondarily for the few people out there who are learning ruby and come from a javascript background. Here are some categorized code samples that basically do the same thing in either language. I’m using Ruby 2.0+.

Comments

// this is a single line comment

/* this is a
   multi-line comment */
# this is a single line comment

# this is a
# multi-line comment

=begin
  another way
  to do multi-line
=end

Variables

In javascript people tend to name their variables starting with a lowercase letter then camel case after that (ie thisIsMyVariable). In ruby, people tend to use all lowercase letters and underscores for separators (ex this_is_my_variable).

var myVariable = "hello there";
my_variable = "hello there"

Arrays

var arr = [1,2,3,4];

arr.push(5);

arr = arr.map(function(a) {
  return a * 2;
});
arr = [1,2,3,4]

arr.push(5)

arr.map! {|i| i * 2} # the `!` saves the result back to the variable

Hashes (objects)

var obj = {
  one: 1,
  two: 2
};

for (var key in obj) {
  // see http://bit.ly/1krXmjL for explanation
  if(obj.hasOwnProperty(key)){
    console.log(key + ': ' + obj[key]);
  }
}

obj.hasOwnProperty('one'); // true
obj = {
  one: 1,
  two: 2
}

obj.each {|key, value|
  puts "#{key}: #{value}"
}

obj.has_key? # true

Functions

function multiply(a, b) {
  return a * b;
}

function addOne(a) {
  return (a || 0) + 1;
}

console.log(multiply(5,10)) // 50

console.log(addOne())       // 1
console.log(addOne(5))      // 6
def multiply(a, b)
  return a * b
end

def add_one(a = 0)
  return a + 1
end

puts multiply(5,10)  # 50
puts multiply 5,10   # 50

puts add_one         # 1
puts add_one 5       # 6

Classes

function Car(year, brand) {
  this.year = year;
  this.brand = brand;
}

Car.prototype.dispayInfo = function() {
  return this.year + ' ' + this.brand;
};

var civic = new Car(2005, 'honda');
civic.dispayInfo(); // 2005 honda
class Car
  attr_accessor :year, :brand

  def initialize(year, brand)
    @year = year
    @brand = brand
  end

  def display_info
    "#{year} #{brand}"
  end
end

honda = Car.new(2005, 'honda')
honda.display_info # 2005 honda

Credits

Here’s a page this inspired some of the content of my post: