Hierarchy of Class Methods
In this chapter, you will learn that class methods have their own inheritance hierarchy. We will also see that the sub classes inherit the class methods from its parent.
Class of a Singleton Class
Let's consider the example we saw in the previous chapter.
class Car
def self.drive
'driving'
end
end
singleton_class = Car.singleton_class
What class is this singleton class an instance of? Let's ask Ruby:
p singleton_class.class
This prints:
Class
Object Hierarchy of Singleton Class
What is object hierarchy of the singleton class? Let's ask Ruby:
p singleton_class.ancestors
This prints:
[#<Class:Car>, #<Class:Object>, #<Class:BasicObject>, Class, Module, Object, Kernel, BasicObject]
There is a whole new hierarchy consisting of singleton classes for Car, Object and BasicObject. Compare this to the ancestors of a normal class:
p Car.ancestors
This prints:
[Car, Object, Kernel, BasicObject]
Now we don't see any singleton classes in this case.
One Level Up
We can go one level up and do a similar experiment.
class Object
def self.drive
p 'driving'
end
end
singleton_class = Object.singleton_class
p singleton_class.ancestors
This prints:
[#<Class:Object>, #<Class:BasicObject>, Class, Module, Object, Kernel, BasicObject]
One More Level Up
Let's go one more level up and repeat a similar experiment.
singleton_class = BasicObject.singleton_class
p singleton_class.ancestors
This prints:
[#<Class:BasicObject>, Class, Module, Object, Kernel, BasicObject]
Practical Use
Let's define a class method in Ruby built-in BasicObject.
class BasicObject
def self.drive
p 'driving...'
end
end
class Car
end
Car.drive
This prints:
driving
Sub classes can call its parent's class methods. If you are familiar with ActiveRecord library of Rails, we often do something like this:
module ActiveRecord
class Base
def self.find(id)
'finding...'
end
end
end
class Car < ActiveRecord::Base
end
Car.find(1)
Now you know how it works.
Same Sender and Receiver
How are we able to call ActiveRecord class methods without a receiver? Can we say Sender and Receiver are the same in this case? For example:
class Car < ActiveRecord::Base
has_many :wheels
end
The concept slightly varies because sub classes can call class methods without a receiver. You can say sub class is a super class. This is the reason why you can consider the sender and receiver to be the same.
Summary
In this chapter, we learned that class methods have their own inheritance hierarchy. We also saw that the sub classes inherit the class methods from its parent.