Since writing about Ruby configuration objects a few months ago, I’ve done a bit of hacking on my original Config class. My main issue with it is that it’s basically serving as a wrapper for a Hash, but it’s a foreign interface. In other words, if you hand a Config object to another developer, he’s going to have to look up the API before he can use it. But that defeats the purpose for writing it in the first place.

The whole idea was to be as flexible as possible, so that configuration objects would be instantly usable and familiar. I don’t want anyone (including myself) to have to think about using the object. It should be easy to use and follow the principle of least surprise as closely as possible.

Also, configuration objects should have powerful methods that allow users to iterate over them, inspect them easily, and merge and compare them with other objects. Obviously Hash provides lots of built-in methods for doing this sort of thing, but it’s not as flexible as I’d like it to be.

The solution? SymbolTable.

SymbolTable is a much more generalized version of my original Config object that actually subclasses Hash. With all of the nice methods of Hash already built-in, a SymbolTable object becomes much more powerful than its Config predecessor and immediately usable.

require 'symboltable'

t = SymbolTable.new

# Lots of convenient accessor methods
t[:a] = 1
t[:a]       # => 1
t['a']      # => 1
t.a         # => 1
t.a = 5
t[:a]       # => 5

# Functions just like a Hash
t.sort.each do |key, value|
  puts "Key #{key} has value #{value}"
end

# You can even merge with another SymbolTable
b = SymbolTable.new
b[:b] = 'hi'
t.merge!(b)

Configuration objects are just one excellent use case for such an object. To install the code, use [RubyGems][rubygems].

$ sudo gem install symboltable

Check out the project on GitHub for more information.