I created yesterday’s post about the wonders of const_missing and method_missing using pure Ruby code. Today I’m going to show you how to do exactly the same thing in C++:
extern "C" {
VALUE ModuleConstMissing(int argc, VALUE *args, VALUE self) {
VALUE const_name = args[0];
VALUE params[] = { rb_const_get(rb_cObject, rb_intern("DynamicProxy")) };
VALUE dynamic_proxy = rb_class_new_instance(1, params, rb_const_get(rb_cObject, rb_intern("Class")));
rb_funcall(self, rb_intern("const_set"), 2, const_name, dynamic_proxy);
return dynamic_proxy;
}
__declspec(dllexport) void Init_RubyBridge() {
rb_require("c:\\dev\\rubybridge\\rubybridge\\rb_library.rb");
rb_define_method(rb_cModule, "const_missing", RUBY_METHOD_FUNC(ModuleConstMissing), -1);
}
}
The rb_require call lets me reference the rb_library.rb file that contains the definition of the DynamicProxy class that I showed you in yesterday’s post.
The rb_define_method method lets me override the default implementation of Module.const_missing. The rb_cModule constant is a reference to the built-in class Module that’s declared in ruby.h. I use the RUBY_METHOD_FUNC macro to pass the address of the ModuleConstMissing function to the Ruby interpreter. The last parameter, -1, is used to tell Ruby to call ModuleConstMissing using a variable-length parameter list.
In the ModuleConstMissing method, I first need a reference to the DynamicProxy class object. This is done by calling rb_const_get, and passing the DynamicProxy symbol. A Ruby symbol is simply an interned string. I use the rb_intern method to intern / retrieve the ID of the interned string.
Next, I need to create a new anonymous class object via Class.new. I can create a new object using the rb_class_new_instance method. Notice how I pass a reference to the DynamicProxy class object to Class.new, which tells Ruby to create a new class that derives from DynamicProxy.
Finally, I assign the newly created class object to the missing constant name that was passed to me from Ruby. The rb_funcall method lets you call an arbitrary method, and uses the C varargs calling convention to let you pass an arbitrary number of parameters (2 in this case) to the method.
These are pretty common usage scenarios for the core Ruby extension APIs that you’re likely to use. There’s also rb_eval_string if you want to execute Ruby code defined inside of a string as well.