Inherited called at different times

Hi.

I have encountered a strange phenomenon about when self.inherited is
called. Take the following code:

class Base
def self.inherited(sub)
p “Base is being inherited”
end
end

class A < Base
p “Declaring A”
end

B = Class.new(Base) do
p “Declaring B”
end

To my surprise, this prints (in ruby 1.8.4)
“Base is being inherited”
“Declaring A”
“Declaring B”
“Base is being inherited”

I was expecting that “Base is…” and “Declaring…” would alternate
nicely.

Although to me that looks like a bug, I presume it isn’t, but I would
greatly appreciate a justification for this behaviour. Note that the
documentation on inherited is not clear on when it is supposed to be
called.

If someone wonders why I care… well a rails plugin I use calls
read_inheritable_attribute and write_inheritable_attribute. These are
defined in an extension to Class that uses inherited and because of the
calling sequence, it works only for the usual declaration but not for
the anonymous one.

Thanks,

Marc-André Lafortune
http://www.marc-andre.ca