When business logic dictates that something only happens on Saturday, this snippet can help keep your code and tests legible.

module DatePredicates
  Date::DAYNAMES.each_with_index do |day_name, i|
    define_method "#{day_name}?" do i == wday end
  end
end
 
class Date
  include DatePredicates
end

Date.today.Tuesday?
=> true

ActionScript’s ExternalInterface is a powerful tool, allowing you to execute and retrieve results from JavaScript in the browser.

Recently however, a strange bug was encountered where Flash running in one part of a page was exhibiting strange rendering issues, such as pieces of the background failing to draw, and Sprites flickering when ExternalInterface calls were made. To make things even more puzzling, the Flash exhibiting the rendering issues was not the one making the calls.

At first it seemed the issue was caused by css, as it only appeared when adding DOM nodes to a parent node styled overflow: auto. After further investigation, it was found found that manipulating the DOM within the ExternalInterface callback was the culprit.

In order to prevent the flickering, it was necessary to decouple the ExternalInterface call from the DOM work. The fix itself was simple.

var client = new Client();
function notifyClient() {
  var arg = arguments[0];
  setTimeout(function() { client.notify(arg); }, 0);
}

Notice how a local is explicitly created to lift out the first argument passed to the JavaScript function instead of using a named argument. In some browsers it was found that named locals were not threaded through to the client.

Using setTimeout with a delay of 0 simply schedules the provided anonymous function to be executed as soon as the singly-threaded JavaScript interpreter is available.

Whenever the result of an ExternalInterface call is not needed for consumption by ActionScript, consider using setTimeout to decouple the work performed by each component.

I really like Ruby, and I really like how the Prototype library makes javascript more Ruby-like. Ruby’s Hash provides a number of convenient methods that Prototype doesn’t ship with. Here is a small extension that borrows a little from Ruby.

Hash.prototype = Object.extend(Hash.prototype, {
  hasKey: function(key) {
    return this._object.hasOwnProperty(key);
  },
  fetch: function(key, fallback) {
    return (this.hasKey(key) ? this.get(key) : fallback);
  },
  getWithDefault: function(key, fn) {
    return (this.hasKey(key) ? this.get(key) : this.set(key, fn()));
  },
  getOrSet: function(key, val) {
    return (this.hasKey(key) ? this.get(key) : this.set(key, val));
  }
});

First, it should be simple to check for the existence of a key in a Hash, whether or not that key contains a falsy value. Since Prototype 1.6, a Hash’s inner object is stored independently of the Hash objects real keys, such as its methods, so the hasKey implementation will only work with Prototype 1.6.

Next up is fetch, which behaves the same as Ruby’s fetch, returning the value present in the Hash for the provided key if a value exists, and providing your supplied alternative otherwise.

getOrSet does essentially the same thing, but adds the alternative value to the Hash if no value was previously present.

Finally, getWithDefault takes a functional 2nd argument which is invoked only if the provided key is not present in the Hash, which is useful for memoizing expensive work.

Array.prototype.binarySearch = function binarySearch(find, comparator) {
  var low = 0, high = this.length - 1,
      i, comparison;
  while (low <= high) {
    i = parseInt((low + high) / 2, 10);
    comparison = comparator(this[i], find);
    if (comparison < 0) { low = i + 1; continue; };
    if (comparison > 0) { high = i - 1; continue; };
    return i;
  }
  return null;
};

Extending Array with this binarySearch method allows you to re-use the functional arguments to passed to sort to generate the sorted array in the first place.

def with_cwd dir
  original_dir = Dir.pwd
  begin
    Dir.chdir dir
    yield
  ensure
    Dir.chdir original_dir
  end
end

When working remotely from the product stakeholders, its important to be able to iterate rapidly over designs, and to capture evidence of, and reproduce tricky bugs.

A great way to do this is by sharing screenshots, and the best tool for quickly sharing screenshots on Mac is GrabUp.

The tool is implemented as a Preference Pane and monitors for screenshots. When a screenshot is taken (using ⌘ ⇧ 3 for full-screen screenshots, ⌘ ⇧ 4 for regional screenshots, and ⌘ ⇧ 4, space for single-window screenshots) the image is automatically uploaded either to GrabUp’s servers, or to your own FTP server*, and the URL to access the image is placed on your system’s clipboard for pasting.

The free version of GrabUp provides a URL which looks like a PNG, but is actually an ordinary web-page containing your image. Pasting these links in Campfire leaves empty rows, so either upgrade to the Pro version which doesn’t have this problem, or remove the “http://” from the beginning of the link before you send it.

Object property-names in JavaScript must be strings. This may seem obvious, but it has serious repercussions if you’re used to the free-wheeling style of Ruby’s Hash.

a = {};
b = {};
a[b] = null;
console.log(typeof(b));
for (var i in a) {
  console.log(typeof(i));
}

In order to have the flexibility I’m used to, I whipped up this simple Hash that stores both keys and values in separate arrays.

/* JavaScript Associative Array */
function Hash(obj) {
  this.initialize(obj);
}
 
Hash.prototype = {
  initialize: function(obj) {
    this._keys   = [];
    this._values = [];
    if (obj) for (var k in obj) {
      this.set(k, obj[k]);
    }
  },
  set: function(key, value) {
    var i = this._indexOf(key);
    if (undefined == i) {
      this._keys.push(key);
      this._values.push(value);
    } else {
      this._values[i] = value;
    }
    return value;
  },
  get: function(key) {
    return this._values[this._indexOf(key)];
  },
  remove: function(key) {
    var i = this._indexOf(key);
    if (undefined == i) return;
    var s = this._keys.length - 1;
    this._keys[i]   = this._keys[s];
    this._values[i] = this._values[s];
    this._keys.pop();
    this._values.pop();
  },
  hasKey: function(key) {
    return (undefined != this._indexOf(key));
  },
  keys: function() { return this._keys.slice(0, this._keys.length); },
  values: function() { return this._values.slice(0, this._values.length); },
  eachPair: function(func) {
    for (var i = this._keys.length - 1; i >= 0; i--) {
      func(this._keys[i], this._values[i]);
    }
  },
 
  _indexOf: function(key) {
    for (var i = this._keys.length - 1; i >= 0; i--) {
      if (this._isElementSame(key, this._keys[i]))
        return i;
    }
    return undefined;
  },
  _isElementSame: function(ele1, ele2) {
    if (ele1 == ele2) return true;
    if ('string' == typeof(ele1)) return false;
    if (ele1.hasOwnProperty('length')) {
      for (var i = ele1.length - 1; i >= 0; i--) {
        if (!this._isElementSame(ele1[i], ele2[i]))
          return false;
      }
    }
    // TODO: Need to do something smarter for objects
    return true;
  }
}

class Numeric
  def to_ordinal
    to_i.to_s + ((11..13) === (n = to_i.abs % 100) ? 'th' :
      { 1 => 'st', 2 => 'nd', 3 => 'rd' }.fetch(n % 10, 'th'))
  end
end

This code is based on a snippet for generating ordinals. The other examples used a fixed-size array for pulling suffixes. Instead, I use the 2-parameter version of Hash#fetch to supply a default for most numbers.

It is frequently desirable to represent bidirectional relationships in web applications, and simple databases are not immediately suitable for this information.

Let’s start with a simple unidirectional example that a database like MySQL handles well.

User 1 wants to be friends with User 2.

A row is inserted into the befriendings table with User 1 as the initiator and User 2 as the recipient.

Now, if your friendships are unidirectional the job is pretty much done. If User 2 wants to be friends with User 1, they can initiate a befriending of their own. On Kongregate, users you have befriended are called “Friends”, and users who have befriended you are called “Fans”

class User < ActiveRecord::Base
  has_many :initiated_befriendings,
    :class_name => :Befriending, :foreign_key => :initiator_id
  has_many :received_befriendings,
    :class_name => :Befriending, :foreign_key => :recipient_id
  has_many :friends, :through => :initiated_befriendings,
    :source => :recipient
  has_many :fans, :through => :initiated_befriendings,
    :source => :initiator
end

However, sometimes you want to follow a friendship model more like the one used by Facebook or MySpace, where all friendships are bidirectional.

Both of these sites implement a relationship-confirmation step before any relationship is finalized. For simplicity’s sake, I’ll skip over modeling that step, but suffice it to say, pending relationships are best stored separately from confirmed relationships. Attempting to mix the two needlessly mingles data and complicates application logic.

Let’s assume any user has the ability to initiate the bidirectional relationship. Now, in the befriendings table, we technically have all the information necessary to list all friends of User 1, and all friends of User 2.

SELECT * FROM befriendings WHERE initiator_id = 1 OR recipient_id = 1 ORDER BY created_at;

SELECT * FROM befriendings WHERE initiator_id = 1
UNION SELECT * FROM befriendings WHERE recipient_id = 1 ORDER BY created_at;

In the first case, only one index can be used (on either initiatior_id, or on recipient_id), and in both cases, the ORDER clause necessitates a filesort on the results.

So the simplest approach here would be to simply duplicate the relationship data in another row, swapping the initiator and recipient ids. This is okay, but starts to fall apart as store more information about the relationship itself. For example, imagine we store a compatibility score between the two users, as last.fm does.

This information would need to be duplicated, as well as keeping the the various timestamps in-sync. Indices against these fields would bloat unnecessarily.

Instead, we can move the duplicated information to a dedicated table, eliminating indices on the relationships table itself. The column by which results are ordered is moved from the relationships table to the dedicated table.

class Befriending < ActiveRecord::Base
  belongs_to :initiator, :class_name => :User
  belongs_to :recipient, :class_name => :User
  after_create do |b|
    BefriendingEdge.create!(:user => b.initiator, :befriending => b)
    BefriendingEdge.create!(:user => b.recipient, :befriending => b)
  end
end
 
class BefriendingEdge < ActiveRecord::Base
  belongs_to :user
  belongs_to :befriending
end

Users then access their list of friends through a :friends association and can access the rich information about the relationship itself through the :befriendings association. The befriending_edges table’s indices are simple and very efficient, and looking up befriendings uses a single primary key, and looking up friends uses two primary keys.

class User < ActiveRecord::Base
  has_many :befriending_edges
  has_many :friends, :through => :befriending_edges, :source => :user
  has_many :befriendings, :through => :befriending_edges, :source => :befriending
end