Callback limitations with `inherited`

class C
def self.inherited(subclass)
puts “#{self} just got subclassed by #{subclass}.”
end
end
class D < C
end

The limits of the inherited callback:

Everything has its limits, including the inherited callback. When D
inherits from C, C is D’s superclass; but in addition, C’s singleton
class is the superclass of D’s singleton class. That’s how D manages to
be able to call C’s class methods.But no callback is triggered. Even if
you define inherited in C’s singleton class, it’s never called.

can anyone help me what the lines above inside ** means?

On Mon, May 13, 2013 at 1:23 PM, Love U Ruby [email protected]
wrote:

Everything has its limits, including the inherited callback. When D
inherits from C, C is Ds superclass; but in addition, Cs singleton
class is the superclass of Ds singleton class. Thats how D manages to
be able to call Cs class methods. But no callback is triggered. Even if
you define inherited in Cs singleton class, its never called.

can anyone help me what the lines above inside ** means?


Posted via http://www.ruby-forum.com/.

So D is sublcassing C. This means that C’s instance methods can be
called
from instances of D, so D’s superclass is C.

BUT, notice that C’s singleton methods can also be called from D. So we
can
infer that D’s singleton class’s superclass is C’s singleton class:

D.singleton_class.superclass == C.singleton_class # => true

So when we subclass, we can see that there are actually two classes who
get
their superclass changed. We might expect, then, that if we defined the
inherited method on C’s singleton class, that it would be called,
because
D’s singleton class subclasses it:

class C
class << self
def self.inherited(subclass)
puts “C’s singleton class just got subclassed by #{subclass}”
end
end
def self.inherited(subclass)
puts “#{self} just got subclassed by #{subclass}.”
end
end

However, only C.inherited is called, not C.singleton_class.inherited

FWIW, I think it’s probably always a bad idea to use hooks like this. I
just can’t think of anything good you can do with it (see Rails for an
example of how even seemingly good uses become abuse).

Josh C. wrote in post #1108884:

On Mon, May 13, 2013 at 1:23 PM, Love U Ruby [email protected]
wrote:

Thanks for your time.

So when we subclass, we can see that there are actually two classes who
get their superclass changed. ** We might expect, then, that if we
defined theinherited method on C’s singleton class, that it would be
called,because
D’s singleton class subclasses it:** – Yes I thought that and also what
would be the reason not to happen it with singleton class? that’s my
curiosity.

class C
class << self
def self.inherited(subclass)
puts “C’s singleton class just got subclassed by #{subclass}”
end
end
def self.inherited(subclass)
puts “#{self} just got subclassed by #{subclass}.”
end
end

However, only C.inherited is called, not C.singleton_class.inherited