2. The first step of rubification

The first step is to convert our Objective-C Cocoa application into a RubyCocoa application. Our application will need to have a Ruby interpreter and the RubyCocoa bridge code built into it. To get them, make the following changes:

  • Add the RubyCocoa framework to your project.
    • In the ‘Groups & Files’ section on the left side of the Project window, expand the ‘Frameworks’ group,
    • Right-click (or Ctrl-click) on the ‘Linked Frameworks’ group, and choose ‘Add -> Existing Frameworks…’
    • Find and add ’/System/Frameworks/RubyCocoa.framework’
  • Replace main.m with the following code:
main.m [Objective-C]
#import <RubyCocoa/RBRuntime.h>

int main(int argc, const char *argv[])
{
    return RBApplicationMain("rb_main.rb", argc, argv);
}
  • Add a new file to your project named rb_main.rb. Give it the following contents:
rb_main.rb [ruby]
require 'osx/cocoa'

def rb_main_init
  path = OSX::NSBundle.mainBundle.resourcePath.fileSystemRepresentation
  rbfiles = Dir.entries(path).select {|x| /\.rb\z/ =~ x}
  rbfiles -= [ File.basename(__FILE__) ]
  rbfiles.each do |path|
    require( File.basename(path) )
  end
end

if $0 == __FILE__ then
  rb_main_init
  OSX.NSApplicationMain(0, nil)
end

Now build and test your application. Everything should work just as before, but your application now has a hidden and very special power—it can run Ruby code. We’ll use this in the next three chapters to convert the three classes Controller, CustomWindow, and CustomView one-by-one into Ruby, and then in the next chapter to make some fun and easy enhancements. We’ll convert the classes one at a time so that we can catch any problems that appear along the way.

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

Comments (2) post
  1. John McIntosh Thu Feb 07 23:07:09 +0000 2008

    When I follow the instructions above, I get two errors when I try to build the application. I think I’m not adding the RubyCocoa framework to my project. How do I do that?

    The two errors are: “_RBApplicationMain”, referenced from: _main in main.old: symbol(s) not found and …failed StandaloneExecutable.LinkUsingFileList /Users/john/Desktop/RoundTransparentWindow/build/Development/RoundTransparentWindow.app/Contents/MacOS/RoundTransparentWindow …

  2. John McIntosh Sat Feb 09 22:14:16 +0000 2008

    I have no idea what I did wrong, but rebuilding the project from scratch solved it.