Skip to content

Instantly share code, notes, and snippets.

@lightsuner
Created October 16, 2014 10:06
Show Gist options
  • Save lightsuner/4f7656d62a8b06295530 to your computer and use it in GitHub Desktop.
Save lightsuner/4f7656d62a8b06295530 to your computer and use it in GitHub Desktop.
After Inherited callback
module App::AfterInherited
# Ruby 2.1
# http://stackoverflow.com/questions/7093992/how-to-have-an-inherited-callback-in-ruby-that-is-triggered-after-the-child-clas?answertab=active#tab-top
# http://t-a-w.blogspot.com/2007/04/settracefunc-smoke-and-mirrors.html
# end - module/class definition ended
# usage:
#
# class A
# extend App::AfterInherited
#
# def self.inherited(child)
# after_inherited do
# puts "XXX - after YYY"
# end
# end
# end
#
# class B < A
# puts "YYY"
# # .... code here can include class << self, etc.
# end
#
# Output:
# => YYY
# => XXX - after YYY
#
def after_inherited(child = nil, &block)
line_class = nil
set_trace_func -> (event, file, line, id, binding, classname) do
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
block.call(child)
end
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment