MacRuby custom initializers
Just opened MacRuby this afternoon; man is ever GOOD! However, I ran into some difficulties while trying to extend an old project with MacRuby-fu. Here's the deal:
So I have a superclass in Objective-C that looks like this:
@implementation Foo
- (id) init {
if (self = [super init]) {
//Do nothing, don't have enough data...
}
return self;
}
- (id) initWithName:(NSString*)n andLocation:(NSString*)loc andSomethingElse:(Bar*)b {
if (self = [super init]) {
//Set a LOT of internal state...
}
return self;
}
@end
So, in the ruby file, we'll name it Mung.rb, which looks like this:
class Mung < Foo
def initWithSomethingElse(else, andEvenMore:more)
super.initWithName("Moop", andLocation:else, andSomethingElse:more.addVal(42))
self
end
end
When I go to the Mung instance (myObj = Mung.alloc.initWithSomethingElse ("Boo", andEvenMore: "US"), the runtime explodes telling me that there is no method called initWithSomethingElse.true in Mung super, but that means I cannot define custom initializers in ruby files. My current workaround is to provide a uniform initializer that accepts a hash and then separate subclasses parse the hash as needed. I don't like this approach and would like to: A. Explanation of that why is "initWithSomethingElse" ever called super, and B. If no direct solution can be applied, there is an alternative workaround. Thanks guys!
source to share
You cannot call the super version of another method from a method in MacRuby. The super keyword respects Ruby semantics and only sends a call to the super version of the current method.
In your case, you can send initWithName: andLocation: andSomethingElse: directly to yourself, and if necessary, you can override this selector in the class and call super accordingly.
source to share