I have this really annoying habit of composing emails that refer to an attachment, only to realize after sending the message that I forgot to include the attachment. So I wrote an attachment scanner plugin for Apple’s Mail.app. The plugin itself is nothing special. It just checks if there’s an attachment, and if there isn’t, makes sure you aren’t using certain words in the message body (basically, attach, attachment, and the like).
What is particularly cool, however, is how the plugin works! It’s written in python (using PyObjC) as a .mailbundle, so when Mail starts up, it will load the plugin. The plugin then creates a subclass of the WebMessageEditor class that Mail uses for, well, the message editor window. It then redefines the send: message to perform its checks, and if they all pass, call its parent’s send: method. On its own, that’s nothing special. What’s cool is how I get Mail to use my WebMessageEditor instead of the one it was compiled to use.
Enter the Objective-C runtime. Objective-C supports a notion of class posing, whereby a subclass can pretend to be (or, to pose as) its parent class. Thus, whenever the code instantiates the parent class, it actually instantiates the subclass. Now, when Mail creates a new WebMessageEditor window, it actually creates my WebMessageEditor window, which adds in my attachment checking hooks. How cool is that?!