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 * ', '}"
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     #
 4 end
 5 obj = get_me_my_object
 6 obj.puts 'Hello there'
 7 = "Puddin'head Wilson"
 9 # prints:
10 obj.puts: Hello there
11 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 /pattern/
3 # prints:
6 (?-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 { |arg| arg.inspect }, so you can tell strings and symbols apart.

Back in OLE-land, I replaced all instances of the selection object with'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?