Ruby: class inheritance

Ruby on rails is an programming language highly class oriented.
Indeed, everything is a class. Even a class.

Today we gonna take a look a inheritance.
What happen when you do not specify inheritance ?
What does "class << self" mean ?


Let's create a class

class Hello
end

Hello.superclass
=> Object

Do you know it's equivalent to

class Hello < Object
end

Hello.superclass
=> Object

Loading issue

Based on previous example, we can figure out that there is an implicite inheritance. Let's play a bit more.

This code works

class World
end

class Hello < World
end

## Let's say we reopen later Hello class
class Hello
  def funk
    # do something
  end
end

This code doesn't work

class World
end

class Hello
end

## Let's say we reopen later Hello class
class Hello < World
  def funk
    # do something
  end
end
=> TypeError: superclass mismatch for class Hello

When you do not specify class inheritance, then :

  • If the class already exist then Ruby just reopen it with the same inheritance
  • Else a new class is created and by default inherit from Object

That's why we get an exception in second example.

Why is it important ?

If you open one day (you did !) some gem source code, you'll notice that the 'lib'.rb file start with lots of requires. It's to force loading order to prevent this kind of problems.

However in rails, you do not do that for you controllers or models right ? It's because all of your class inherit from something.

If you meet this kind of errors, it means you have to :

  • Force inheritance on your class to be sure whatever loading order, they will be defined inheriting what you want
  • Force loading order with require

One last trick

Do you know what means :

class Hello
  class < self
    def world!
      puts "#{self} world!"
    end
  end
end

It's the same than using def self.world! Except that you write in once, and gather in one place all class methods.

Hello.world!
=> "Hello world!"

Done