Lately I’ve been generating MS Word .docs from text files, with RedCloth and Hpricot (thank you, why, for both of those), and win32ole. It’s been fun, except for the OLE parts: the ruby bridge is great, but the OLE API itself is strange, good documentation is sparse, and things get…flaky, sometimes.

In troubleshooting a bug that turns bold text on and off at the wrong times, I thought “it’d be nice if I could see all the calls that happen to this ‘selection’ object, in order they happen. Maybe I don’t realize I’m turning the ‘bold’ on at the wrong times.” Enter the Echoer:

1 class Echoer
2     def initialize(name)
3         @name = name
4     end
5     def method_missing(method_name, *args)
6         puts "#{@name}.#{method_name}: #{args * ', '}"
7         Echoer.new("#{@name}.#{method_name}")
8     end
9 end

The Echoer is a stand-in for a regular object. Whenever a method is called on it, it prints its own name, the name of the method called, and the arguments.

 1 def get_me_my_object
 2     # RealObject.new
 3     Echoer.new('obj')
 4 end
 5 obj = get_me_my_object
 6 obj.puts 'Hello there'
 7 obj.name = "Puddin'head Wilson"
 8 
 9 # prints:
10 obj.puts: Hello there
11 obj.name=: Puddin'head Wilson

Each method call returns a new Echoer, whose name is based on its name, and the method name, so you can chain method calls.

1 obj.next.upcase.match /pattern/
2 
3 # prints:
4 obj.next:
5 obj.next.upcase:
6 obj.next.upcase.match: (?-mix:pattern)

I should probably make Echoer a BlankSlate object, but I haven’t run into a need for it just yet. I could also inspect the method’s arguments with args.map { |arg| arg.inspect }, so you can tell strings and symbols apart.

Back in OLE-land, I replaced all instances of the selection object with Echoer.new('selection'), re-ran my code, and watched the output. I still haven’t found the source of the bug, but at least I know I’m not turning bold on or off when I don’t expect to.

Thanks to Michael Feathers for this idea. He wrote on the Beautiful Code blog about Spelunking Ruby Methods with Pebbles, but it seems O’Reilly took the blog down. All that’s left are the links from sites like reddit…does anyone know if the content is floating around somewhere out there?