Building extention with multiple classes

Hello,

I have been successful at building a ruby extension that contains one
new class and now I would like to build multiple classes. I am wondering
what is the best way to do this.

If my new class is called ‘NewClass’ (defined in NewClass.c) and I put
create_makefile(“NewClass”) in my extconf.rb then I can require
“NewClass” in my app.rb and it will load NewClass.so.

This seems to work fine. But, now suppose I have another file called
NewClassTwo.c which defines class ‘NewClassTwo’. I would also like to
use this class in my Ruby app.rb.

I haven’t found a way to make this work.

It is starting to look to me like a given extension can only implement a
single class. Is this true? In other words, I think that the name passed
to require() must be identical to the name of the class you want to
load. So, for example, is it true that one call to require can only load
one class?

Do I have to build each class separately into its own extension .so
library and then include them all?

I’ve got to create at least 50 classes to cover all my C functionality.
This would mean 50 calls to require() in my .rb code. This doesn’t seem
right.

Much thanks for the help in advance.

Richard

Hi Joel,

Thank you very much. Most helpful.

Richard

On 04/29/2011 02:39 PM, Richard Shinn wrote:

Hello,

I have been successful at building a ruby extension that contains one
new class and now I would like to build multiple classes. I am wondering
what is the best way to do this.

Take a look at the ext/ dir in ruby’s source. For example, in socket.c:

void
Init_socket()
{
rb_eSocket = rb_define_class(“SocketError”, rb_eStandardError);

 rb_cBasicSocket = rb_define_class("BasicSocket", rb_cIO);

This snippet defines two classes. Farther down you’ll see the
rb_define_method() calls to associate the C functions that implement
methods, and also the C functions themselves. These functions can just
as well be defined in separate .c files in the same dir. They will get
found by extconf.rb (in the create_makefile call, IIRC).

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs