Recent Projects Recap

Just a quick round-up of some recent projects:

Fortress An online Dwarf Fortress style game demo. All open-source JavaScript with an MVC style framework. The dog walks around picking up plants. I guess the rubies are seeds or something. Not really playable yet, but under highly active development.

Pixie JavaScript pixel editor. Added color pallette selection and loading images from server.

Cask of Amontillado Not a recent project, or even any real development on it recently, but an oldie and a goodie.

Now is the time for our first reader survey:

How did you hear about STRd6? (Please answer in the comments.)

Can’t dup NilClass… maybe try `unloadable`

If you’re using a model or controller from an engine in Rails 2.3.2 you may encounter some crazy errors from time to time. Errors like: A copy of ApplicationController has been removed from the module tree but is still active! Or sometimes the even weirder one: can't dup NilClass

In one situation where you get A copy of ApplicationController has been removed from the module tree but is still active! it could be because you’re using a plugin or engine that provides controllers and inherits from ApplicationController. Some of the classes inherited or included in your engine controllers may fail to get unloaded and cause trouble after the first request to your system. Add unloadable inside your controller classes in your engine.

The can't dup NilClass error really tricked me though. It seemed to be saying something about duping nil class but not really. It was a lie! Well, almost. See, I had a model in my engine like this:

class Account < ActiveRecord::Base
  include Authentication::ByCookieToken
  include Authentication::AccountBuddy
  has_many :logins, :dependent => :destroy
  attr_accessible :nickname, :email

And I had a module in my app (not in the engine) like this (sort of a reverse-micro-plugin):

module Authentication
  module AccountBuddy
    def self.included(account)
      account.class_eval do
        has_many :characters

And when I tried to access account.characters it was all “can’t dup NilClass”. But what it really meant to say was: “I’m returning nil instead of an array containing the characters belonging to this account because I became confused during the loading and unloading of all your crazy ass models. -Love, Rails”

So adding a little unloadable also fixes that.

class Account < ActiveRecord::Base
  unloadable # <= That's the ticket!
  include Authentication::ByCookieToken
  include Authentication::AccountBuddy # reverse-micro-plugin 
  has_many :logins, :dependent => :destroy
  attr_accessible :nickname, :email

What a load off.

A better way

Courtesy of Paul (from the comments)

unloadable is now deprecated, I think. As far as I am aware, the “right” way to do this is one of the following:

First, you could put something like this in your plugin’s init.rb file:

# This plugin should be reloaded in development mode.
if RAILS_ENV == 'development'
  ActiveSupport::Dependencies.load_once_paths.reject!{|x| x =~ /^#{Regexp.escape(File.dirname(__FILE__))}/}

Second, you could put something like this in your application’s environment.rb file:

config.reload_plugins = true if RAILS_ENV == ‘development’

If the above did not solve your problem:

Courtesy of Evan Owen (from the comments)

Another possible cause of this problem is that ActiveRecord also defines self.included. In order to ensure that ActiveRecord gets the call and can finish loading the model, a call to super needs to be added to the end of self.included like so:

def self.included(account)
  account.class_eval do
    has_many :characters
  super # fixes the "can’t dup nil" issue

This did not work in my specific case, but may be the correct solution if you are suffering from a similar but different problem.

Adding a Non-null Column with no Default Value in a Rails Migration

This is something that I’ve often needed to do: add a new column to the DB that has a non-null constraint, but also doesn’t have a default value. There are a some options:

  • Forget the DB constraint and use `validates_presence_of` in the model
  • Add a default value for the new column with non-null and then remove the default
  • Add the column without a default value, then alter it to be non-null

The first method of simply using `validates_presence_of` won’t cut it for me because that doesn’t actually make guarantees on the data stored in the DB from interfaces outside the of application.

Adding the new non-null column with a default value and then altering it to remove the default would probably be the best choice if you just need a standard value for all your historic data.

The third method is how I did it, and I like it best for any data that can be computed to a reasonable value to start out.Here’s the source for my migration:

class AddLoginMetricsToAccounts &lt; ActiveRecord::Migration
  def self.up
    add_column :accounts, :last_login, :datetime
    add_column :accounts, :total_logins, :integer, :null => false, :default => 1
    Account.all.each do |account|
      account.last_login = account.created_at!
    change_column :accounts, :last_login, :datetime, :null => false
  def self.down
    remove_column :accounts, :total_logins
    remove_column :accounts, :last_login

I’m adding a last_login column that I want to be non-null, but because it has no default value most DBs won’t allow the new column to be added (it violates data integrity). So the thing is to add the column without a a non-null constraint, populate it with acceptable values, and then to change the column to include the constraint.

Hope this comes in handy!

Pixie – A JavaScript Pixel Editor

As part of this amazing new game that we are working on we have an online pixel editor component. Right now it is a rough proof of concept. The primary goal is to create a simple online editor that provides the right blend of tools to easily create 32×32 pixel images which can then be saved locally or uploaded to the server. You can even load previously uploaded images, sweet!

The inspiration is Pixen, but instead of being Mac-only it will be available online for all platforms. Pixen provides a strong tool set and a great interface, but why be so exclusive about it? I know, right? The browser is the future anyway, and doesn’t crash as often.

Check out Pixie here. The idea is to keep it simple, there are only a few features missing from fullfilling every one of my wildest dreams (undo, selection, semi-transparency). For fun check out the JS code, it was designed with clarity and extensibility in mind. It’s a purely JS/CSS based editor, built using Prototype.js.

Editing images is fun!

Editing images is fun!

To get the images to the server they undergo an amazing (and probably inefficient) journey. Each pixel is read from the “canvas” and put into an ancient (late 90s) JS PNG encoder. That PNG encoder then spits out the image as a png data file which is then base64 encoded and sent to the server. The server base64 decodes the file and saves it to the local file system. Loading images from the server makes it even crazier! Since this ancient PNG encoder doesn’t load PNG data (to my knowledge) the server uses RMagick to read the uploaded image’s pixels and convert them to a JS array of hex color values, then passes that array into a load method back on the client. It’s amazing!

Have fun editing all those little images, and you can even check out the game that goes with it!

Ruby Quiz

So, better late than never I guess… I’ve been Ruby Quizmaster for about two months now.

The Ruby Quiz site is at This is the third incarnation of Ruby Quiz, a weekly quiz that let’s you put your Ruby skills to the test. The first quiz was started by James Edward Grey II, there was also a book Best of Ruby Quiz (Pragmatic Programmers).

Great for keeping your skills of a programmer sharp! Also, there is a submission form for ideas. Please do submit ideas, I’m running out! The more to choose from, the better the quizzes!

Temptation + Convenience = Misdemeanor

My home-boy A-Tang was recently in a car driving back from a party. He asked his friends if he should yell “Boners 5-0” out the window at a policeman who had pulled someone over. The consensus was that he obviously should.

A-Tang: Boners 5-0!

** Lights + Siren **

[Pulled over]

Policecop: I heard someone yell something out the window, do you require any assistance?

Partygoer: Uhh… no officer, we’re all fine here.

Policecop: Well I see you’re missing your seatbelt, that’s a ticket. Do you have your license and registration?

Drivey-Tang: Sorry, I don’t have my license with me…

Policecop: That’s another ticket. [To A-Tang] Are you happy? You just got your friend two tickets.

This story illustrates a point. Regardless if something is a good idea or not, if it is convenient to do and it might be a good idea then it is much more likely to be done than something that is difficult and definitely a good idea. For context check out The Easiest Way to Change People’s Behavior.

This applies a lot to personal habits. Anything within arms distance should be good for you. Tired of always eating a ton of chips and soda? Move them into the garage. Getting distracted by things nearby? Move to a different room or location where distractions are further away.

Here’s the kicker though: being a knowledge worker who needs to use the internet for most tasks distractions are always within arms reach. There might be some programs out there that move the most distracting and least productive parts of the internet away and if so they are probably of some value. Self-restraint will also help, but for maximal productivity it takes more than just that. Other solutions: Put on a business hat when doing business and a party hat when just surfing the net, designate certain computers/locations for work or play and keep them separate; your brain will figure it out if you are consistent. Adding a physical component to the context switch will put it out of arms reach.

Test First: The only way to personally achieve black box testing

Writing tests first is your only opportunity as a developer to black-box test your own code. If you write tests after you write the code then you are too familiar with it’s workings to do successful black-box testing. This doesn’t matter so much in a larger team where you have designated QA and can get other developers to write tests for your code (or in La-La Land as it is called). If you are a solo developer or on a real team where everyone else has their own problems and everyone can barely find time to eat then test first is your only opportunity to black-box test.

Sure, maybe if you’re the best developer in the world your code can’t be improved by testing or otherwise. Maybe if you’re not the best developer your code can’t be improved either, but in the same sense that the Home Improvement boardgame can’t be improved, not a good position to be in.

So don’t listen to Joel and Jeff, well I mean, do listen… and they’ll probably be first to agree that you need to do your own research and find what works for you and not take anything on either side of the argument as gospel.

Using GreasyThug to Answer a Greasemonkey Question

On StackOverflow a user asked: How can I create an object of a class which defined in the remote page?

The page includes code like this (which I entered into Firebug):

function foo(){ = 0; }

Then I verified that it could be read from Greasemonkey with the GreasyThug console by the following expression:

_foo =;
x = new _foo();
Debugging with GreasyThug

Debugging with GreasyThug

This caused a “Not enough arguments” error, whatever the hell that is. Not quite the poster’s actual error. What if we added an argument? “Illegal Value” Bingo! Replicated the issue. Now to solve it.

Let’s try and migrate the function over into the Greasemonkey script zone.

_foo = eval('(' + + ')')
=> function foo(){ = 0; }

That’s the ticket! Now to instantiate and verify:

The magic of a debugging thug
The magic of a debugging thug

Ship it! Holla!

Two Column Google Greasemonkey Script

I remember installing a userscript that would display Google search results in two columns in days of yore. Then one day it stopped working. All the other Google userscripts were massive customize everything about Google ever. I just want two columns homie, and favicons, but I’ve already got the FF plugin for that.

So here it is, the amazing remake that is as good as the original… Two Column Google, nothing fancy, just two columns.

Display Google search results in two columns

Display Google search results in two columns