just a simple dsl to accept a block on a module’s ‘run’ method and eval the contents in the context of the module.
#include <ruby.h>
#include <stdio.h>
VALUE jm_Module;
VALUE
m_run(VALUE self) {
if (rb_block_given_p ()) {
rb_mod_module_eval(0,0,self);
return Qnil;
}
else
rb_raise (rb_eRuntimeError, "must be called with a block");
return Qnil;
}
VALUE
m_hello(VALUE self) {
printf("hello world\n");
return Qnil;
}
void
Init_blocks() {
jm_Module = rb_define_module("Block");
rb_define_module_function(jm_Module, "run", m_run, 0);
rb_define_module_function(jm_Module, "hello", m_hello, 0);
}
equivalent ruby code would be:
module Block module_function def run(&b) module_eval(&b) end def hello puts "hello world" end end
use like this:
Block.run { hello }
contents of block will be executed within context of the module, so can invoke module methods.
Filed under: programming | Tagged: C, dsl, ruby