Tim Hunter
2/13/2005 1:56:00 PM
On 2005-02-13 02:37:33 -0500, craig duncan <craig-duncan@earthlink.net> said:
> I'm relatively new to Ruby (in terms of seriously programming in it)
> and right now i want to create a C extension for the low-level
> ogg/vorbis libraries. I have the basic architecture for this mapped
> out in my head and i'm able to look at the wrapping that someone has
> already done for the higher-level libvorbisfile library.
> At the very beginning of that extension's Init_vorbisfile function it does:
>
> cOgg = rb_define_module("Ogg");
> cVorbisFile = rb_define_class_under(cOgg, "VorbisFile", rb_cObject);
> rb_define_singleton_method(cVorbisFile, "new", vf_s_new, -1);
>
> Looking at this has me a little confused because that's now what i had
> in mind to do. I had no thought of creating a module, and i
> thought i would just create the OggStream class i want to define
> directly with:
>
> cLibOgg = rb_define_class("OggStream", rb_cObject);
>
> I also hadn't identified any need to define "new" as a singleton
> method. So... Can anybody provide me with an at least plausible
> rationale for what advantages there might be in defining a module in
> this situation, and then for using define_class_under to define the
> class... and for creating this one singleton method (all the other
> methods defined after this just use rb_define_method). Maybe the
> vf_s_new function is something that's only supposed to be called once.
> But, limited as my understanding of Ruby is, i don't understand exactly
> the connection between that and defining "new" as a singleton method.
> What exactly does making something a singleton method preclude (trying
> to answer my own questions)? The obvious answer is: creating more than
> one instance. But when that applies to a method... i don't get it
> (this singleton stuff has never been completely clear to me in all its
> nuances).
>
> Groping for an answer some more... does creating an "Ogg" module this
> way allow someone else (like me, in this instance) to also define the
> _same_ module in my extension and if both extensions are loaded at the
> same time they go into the same module namespace and there's some
> benefit in this?
>
> Any insights into any or all of this will be greatly appreciated.
>
> craig
The module is there to prevent namespace pollution. By defining the Ogg
module you are reserving the Ogg namespace instead of inserting your
classes into the top-level namespace. It's a courtesy to your users.
Defining a singleton method called `new' is the old way to define the
`new' class method. In 1.8.0 and later, use the rb_define_alloc_func
function. See the PickaxeII for more information.