How to use Obj-C classes in MacRuby
I am trying to use an external Obj-C class in my MacRuby project, but I can't figure out how to import it. Specifically, I want to use ObjectiveResource inside a MacRuby 0.5 project (since ActiveResource doesn't work - yet).
I have gotten as far as the 'framework' command in MacRuby, but it only seems to apply to actual frameworks.
Questions: where should I install the objective-resource directory? how do I pull these classes 开发者_Python百科inside my ruby code?
Thanks for any help!
You can access the class directly using ClassName.new.
If you have a class named Utilities in your project and it has a method named greeting:, you would call it like so.
util = Utilities.new
puts util.greeting("Good morning")
There is no require or framework declarations required. Amazingly simple isn't it. I discovered this watching the Peepcode screencast on MacRuby.
Also, if you are interested in calling Ruby code from Objective-c, here is an extract from the MacRuby mailing list:
Once the MacRuby runtime is initialized, you can access all your Objective-C objects from Ruby. For example, if you have an Objective-C class named Foo, you can do `Foo.new', etc.
Another possibility is to pass your Objective-C objects to a Ruby method by using [NSObject performRubySelector:]
.
ruby:
class Foo
def test(o)
o.something
end
end
objc:
MyObject *o = [MyObject new]; // where o responds to -something
MacRuby *runtime = [MacRuby sharedRuntime];
id foo_obj = [runtime evaluateString:@"new Foo"];
[foo_obj performRubySelector:@selector(test:) withArguments: o, NULL];
Check out the whole API here: http://www.macruby.org/trac/browser/MacRuby/trunk/include/ruby/objc.h
Thread: http://lists.macosforge.org/pipermail/macruby-devel/2010-April/004715.html
(Edit) That said, perhaps the easiest way is to add a header file for your ruby file, containing your methods equivalents.
Suppose that you have this ruby class:
class Foo
def bar(moo)
"a string like #{moo}"
end
end
so the equivalent header file will be something like that:
@interface Foo : NSObject
- (NSString *)bar:(NSString *)moo
@end
Now, just #import
the header and use your ruby classes as standard Obj-C ones from within your Obj-C code:
NSString *aString;
Foo *myFoo;
aString = [myFoo bar:@"me"];
It may seem weird, but it works. Essentially, the idea is to shut the compiler's mouth and let it compile your code without complaining about missing methods. Then, at runtime, it will just work (I suppose thanks to the dynamic nature of Obj-C itself). By the way, to mimic the ruby typeless behavior, id is your friend in writing methods signatures in the header file.
Did you look at this example of creating an ObjC bundle?
精彩评论