Created
July 20, 2011 21:13
-
-
Save copiousfreetime/1095950 to your computer and use it in GitHub Desktop.
Descendant Tracker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'set' | |
# | |
# Use by either | |
# | |
# class Foo | |
# extend DescendantTracker | |
# end | |
# | |
# or | |
# | |
# class Foo | |
# class << self | |
# include DescendantTracker | |
# end | |
# end | |
# | |
# It will track all the classes that inherit from the extended class and keep | |
# them in a Set that is available via the 'children' method. | |
# | |
module DescendantTracker | |
def inherited( klass ) | |
return unless klass.instance_of?( Class ) | |
self.children << klass | |
end | |
# | |
# The list of children that are registered | |
# | |
def children | |
unless defined? @children | |
@children = Set.new | |
end | |
return @children | |
end | |
# | |
# Find one of the child classes by calling the given method | |
# and passing all the rest of the parameters to that method in | |
# each child | |
def find_child( method, *args ) | |
klass = children.find do |child| | |
child.send( method, *args ) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment