Possible Duplicate:
ruby: can I have something like Class#inherited that's triggered only after the class definition?
class A
def self.inherited(child)
puts "XXX"
end
end
class B < A
puts "YYY"
end
prints out
XXX
YYY
I'd prefer
YYY
XXX
if I could get it somehow.
Whenever you want to call parent class method of the same name so you can simply write super or super(). Example: Ruby.
The Ruby class Class inherits from Module and adds things like instantiation, properties, etc – all things you would normally think a class would have. Because Module is literally an ancestor of Class , this means Modules can be treated like classes in some ways. As mentioned, you can find Module in the array Class.
In Ruby, a class can inherit from one other class. This is called single inheritance. Some languages have support for multiple inheritance, which means a class can inherit from multiple classes.
You can trace until you find the end of the class definition. I did it in a method which I called after_inherited
:
class Class
def after_inherited child = nil, &blk
line_class = nil
set_trace_func(lambda do |event, file, line, id, binding, classname|
unless line_class
# save the line of the inherited class entry
line_class = line if event == 'class'
else
# check the end of inherited class
if line == line_class && event == 'end'
# if so, turn off the trace and call the block
set_trace_func nil
blk.call child
end
end
end)
end
end
# testing...
class A
def self.inherited(child)
after_inherited do
puts "XXX"
end
end
end
class B < A
puts "YYY"
# .... code here can include class << self, etc.
end
Output:
YYY
XXX
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With