Chapter 11. MacRuby in Objective-C Projects

MacRuby is great, but you might already have a Cocoa application written in Objective-C. Rewriting all of it in MacRuby would probably be fun, but maybe not really wise. You might also want to experiment with MacRuby without fully committing to it yet. Another reason to mix the two languages is if you want to better test your Objective-C code, but are not pleased by the existing Objective-C tools. Whatever reason you have, MacRuby is really easy to use within your existing app.

API

MacRuby is a framework, so to use it in your Objective-C project, you just need to add it to your project and import the headers:

#import <MacRuby/MacRuby.h>

Once you have added the framework and imported the headers, you can call out to files or snippets of MacRuby from Objective-C. Let’s take a minute to look at the API provided by the MacRuby framework:

#import <Foundation/Foundation.h>

@interface MacRuby : NSObject

/* Get a singleton reference to the MacRuby runtime, initializing it before if
 * needed. The same instance is re-used after.
 */
+ (MacRuby *)sharedRuntime;

/* Evaluate a Ruby expression in the given file and return a reference to the
 * result.
 */
- (id)evaluateFileAtPath:(NSString *)path;

/* Evaluate a Ruby expression in the given URL and return a reference to the
 * result. Currently only file:// URLs are supported.
 */
- (id)evaluateFileAtURL:(NSURL *)URL;

/* Evaluate a Ruby expression in the given string and return a reference to the
 * result. ...

Get MacRuby: The Definitive Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.