Home > General, JRuby, Programming, Ruby > Writing your own JRuby extension. Part II: Creating your first class.

Writing your own JRuby extension. Part II: Creating your first class.

March 12th, 2010 Serabe Leave a comment Go to comments

3783473433 98d837343a m Writing your own JRuby extension. Part II: Creating your first class.
What’s the point of coding a JRuby extension if you don’t create classes? Well, I cannot think of any case, but if you find one, please, let me know.

Do you remember Java’s classes hierarchy? If so, you’ll realize  that Java objects inherit from java.lang.Object by default but that is not actually what we need. But how can we tell JRuby that our object inherits from Object, the king of Ruby world? The answer is so simple: just extend RubyObject! (There is a RubyBasicObject too) Taken from Nokogiri::XML::Node:

Of course, you can extend any other class, as long as it is a “Ruby object”. For example, Nokogiri::XML::Document extends from Nokogiri::XML::Node, and we do not need to do anything special to reflect it, just extend XmlNode like XmlDocument does:

After talking a bit about hierarchy, let’s talk about Java constructors. At least two parameters are needed: a org.jruby.Ruby object and a org.jruby.RubyClass object. Being the importance of the former quite obvious, the reason for the latter may not be so clear. Let me show you some real world code: Nokogiri::XML::Node’s dup method. Take a look at the following test:

Both new and dup methods in subclass rely on Nokogiri::XML::Node’s. In here, you can see the this snippet of code:

The rb_obj_class method returns the class of an object, in this case, self. This way, the new node will be an instance of the same class as the original node. That’s the reason a RubyClass is needed in the constructor, in order to know which is the actual class being instantiated.

By the way, do not forget to call super with the Ruby and RubyClass objects.

Next step: creating methods.

cc Writing your own JRuby extension. Part II: Creating your first class. photo credit: quinn.anya

article clipper Writing your own JRuby extension. Part II: Creating your first class.
 
  1. NilsH
    March 29th, 2010 at 22:45 | #1

    Heyho!

    Im looking forward to the next part of this tutorial!

    I think i will not get used to it fast enough to help properly with nokogiri, but lets see what happens,…

    University takes lots of time. :/

    Greetz,
    Nils

  1. No trackbacks yet.