I understand the regular method lookup path i.e. class, superclass/module, all the way up to BasicObject. I thought it was true for singleton version of the chain also but doesn’t seem the case when you mixin a module in the meta-chain. I’d appreciate if someone can explain why in the following example Automobile module’s banner method is called instead of its singleton version when I have included this module in Vehicle’s eigenclass.
module Automobile
def banner
"I am a regular method of Automobile"
end
class << self
def banner
"I am a class method of Automobile"
end
end
end
class Vehicle
def banner
"I am an instance method of Vehicle"
end
class << self
include Automobile
def banner
puts "I am a class method of Vehicle"
super
end
end
end
class Car < Vehicle
def banner
"I am an instance method of Car"
end
class << self
def banner
puts "I am a class method of Car"
super
end
end
end
puts Car.banner
# I am a class method of Car
# I am a class method of Vehicle
# I am a regular method of Automobile
First of all,
includedoes not include eigenclass methods as you might expect. Consider:Note that this is consistent with the behavior of classically defined class methods:
A common idiom is to define the class methods in a submodule and then trigger a call to
extendwhen the module is included:The second thing to note is, that you are really including the instance methods of
Automobileinto the eigenclass ofVehicle, thus the instance methods ofAutomobileturn into (eigen)class methods ofVehicle.Your
Carclass basically has nothing to do with all this. The only thing to note here is, that class inheritance also makes class methods available, whereasincludedoes not. Example: