3. Wow, that was easy. So what do you think?

Despite its simplicity, there are some disadvantages to the RubyCocoa approach:

  • Importing the class is ugly. Instead of simply require ‘jukebox’, we must also import the RubyCocoa bridge (require ‘osx/cocoa’) and then explicitly import our jukebox class using OSX::ns_import :Jukebox. If you want, you can hide this in a Ruby module that does the importing behind the scenes. But for me, the objective is to write as little glue code as possible, so I can live with a little discomfort here.
  • We have to use RubyCocoa/Objective-C object allocation and initialization. Instead of calling Jukebox.new to create our jukebox objects, we have to perform the standard Objective-C two step initialization. First call alloc, then the init function, in this case initWithUnit.
  • If you work through the example in Programming Ruby, you’ll see Dave Thomas illustrate a way to pass a block into the jukebox seek function. The seek function then calls that block back to report progress. This is not (yet?) possible with RubyCocoa. I’ve dug around a bit in the RubyCocoa source code and didn’t find anything that seemed to wrap blocks. So if you need that capability, you have to use the C-level interface.
  • The RubyCocoa bridge code is undoubtably slower than a custom-coded C extension. To me, that’s not a big issue. It would only be a problem if I’m calling across the boundary a lot, and if I am, then I’d want to reorganize my code to make those calls from Objective-C. Not messing with glue code gives me more time to do that.

Now let’s consider the advantages of writing Ruby extensions with RubyCocoa:

  • You can call the exact same interface from Objective-C. “Wait,” you say, “I could have called my original interface from Objective-C!” True, but for a non-trivial example, writing that Objective-C wrapper will probably force you to clean up your interface a bit as well (ask a QuickTime programmer about this!). And hey, now your slithery friends can also use your code from Python with PyObjC.
  • It only works on a Mac. “Wait”, you say again, “isn’t that a disadvantage?” Yes, but do you really need any more excuses to switch?
  • It is really really really simple. If you need to make the comparison for yourself, the corresponding C code is in the pickaxe book on pages 290-293 (the Extending Ruby chapter runs from pages 275-314).

Thanks for reading! If you have any comments or suggestions, please send them to me at the link below.

Tim Burks

Did you find an error? Is something missing? Post your comment or suggestion below!

Comments (1) post
  1. Phil Kanter Sun Sep 17 09:11:00 +0000 2006

    Could the use of libffi speed up RubyCocoa and make it even smarter at the same time?

    http://chopine.be/lrz/diary/2006-09-15_RubyCocoa-and-libffi.html