Search code examples
crubyruby-c-extension

Defining classes in modules with the Ruby C API


I am trying to define a class inside a module with the Ruby C API. However, the way I have seen this done all over the net doesn't seem to work for me. Specifically, the top-level module gets created but the class can't be found inside the module. Here's my C file:

#include <ruby.h>

static VALUE mTree;
static VALUE cNode;

VALUE hello_world(VALUE klass)
{
    return rb_str_new2("hello world");
}

void Init_tree()
{
  mTree = rb_define_module("Tree");
  cNode = rb_define_class_under(mTree, "Node", rb_cObject); 
  rb_define_method(cNode, "hello_world", hello_world, 0);
}

Here's my extconf.rb:

require 'mkmf'
create_makefile('tree')

Here's my test script:

require 'tree'
puts Tree        # => Tree
puts Tree::Node  # => uninitialized constant Tree::Node (NameError)

Can anybody help?


Solution

  • This is strange, your example works for me:

    → ruby extconf.rb     
    creating Makefile
    → make          
    linking shared-object tree.bundle
    → irb
    >> $:<<'.'
    => [...]
    >> require 'tree'
    => true
    >> Tree
    => Tree
    >> Tree.class
    => Module
    >> Tree::Node.class
    => Class
    >> Tree::Node.new.hello_world
    => "hello world"