Last active
December 14, 2015 22:29
-
-
Save agerwick/5158730 to your computer and use it in GitHub Desktop.
Listing all subclasses of a class, excluding the class itself.
This is useful for listing all Models of a database adapter, such as Ohm::Model.subclasses and ActiveRecord::Base.subclasses .
This file contains 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
class Class | |
def subclasses | |
class_hash = {} | |
ObjectSpace.each_object do |obj| | |
if Class == obj.class | |
# remove first item from ancestors, which is the class itself - it's wrong to say a class is a subclass of itself | |
if obj.ancestors[1..-1].include? self | |
class_hash[obj] = true | |
end | |
end | |
end | |
class_hash.keys | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment