Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you change the default inheritance of classes in Ruby?

As a little hobby project, I'm trying to build up my own object system. I was wondering if there is a way of changing the default inheritance of all classes from Object to my base class Entity, so that whenever I create a new class I don't have to explicitly say class Thing < Entity; ideally, I would just be able to say class Thing and have its default superclass be my Entity class.

like image 635
Daniel Brady Avatar asked Jul 01 '26 08:07

Daniel Brady


1 Answers

Sure you could do this by modifying the relevant part of the Ruby source and recompiling Ruby:

VALUE
rb_define_class_id(ID id, VALUE super)
{
    VALUE klass;

    if (!super) super = rb_cObject;  // <-- where the default is set
    klass = rb_class_new(super);
    // ...

But that’s a huge hassle and requires patching and running a custom Ruby and probably has a lot of gotchas and things that are hard-coded to assume Object is the default.

And, on top of that, what’s the point? If you replace Object with something else as the default superclass, every class—including those in Ruby core—will now inherit from this new default superclass. You could get the same effect (just without the different name) far more easily and without needing a custom Ruby by just changing Object itself. That’s the beauty of being able to reopen classes! For example:

class Object
  def foo
    'bar!'
  end
end

class A; end

A.new.foo  #=> 'bar!'

If you wanted to be kind you might even just put all the relevant methods in an Entity module instead of a class and then include it into Object.

like image 103
Andrew Marshall Avatar answered Jul 05 '26 21:07

Andrew Marshall