Thursday, March 26, 2009

Hi there. I'm back after a long hiatus. Since my last post, I've moved across the country from Buffalo, NY to Berkeley, CA, had 2 jobs, and become a father. So I ask your forgiveness for the long period between posts.

On to some code. I like to use Constants in Ruby whenever feasible. It's a logical and readable-to-the-next-coder way to store information in a way that indicates it should not change. It also gets some compile-time optimization for speed, and takes up less memory as a datum shared across the various instances of a class.

I'm particularly fond of constant Hashes for small lookup tables. Let's imagine some generic Rails controller with this code snippet:

Hashes in Ruby have a handy method called default= that sets what the default looked-up value should be when the key for the lookup is not found in the Hash. (You can think of the default default as nil, if that makes any sense.) However, default= returns the default value, rather than the new Hash. So this gets problematic:

This allows us to define the particular cases with explicit Hash pairs, set a default value, and keep everything in Constant world. Depending on the particulars, we could instead go with either a class variable (@@banal_message_for) or a class method.

I still like constant-from-a-lambda, though - even despite the somewhat off-putting complexity of the lambda/call syntax. It makes it clear that we're dealing with constant data, and the complexity from the call syntax seems less egregious to me than having an additional method whose only purpose is to be called once at app start.