Skip to content

Instantly share code, notes, and snippets.

@copiousfreetime
Created July 20, 2011 21:13
Show Gist options
  • Save copiousfreetime/1095950 to your computer and use it in GitHub Desktop.
Save copiousfreetime/1095950 to your computer and use it in GitHub Desktop.
Descendant Tracker
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