Skip to content

Instantly share code, notes, and snippets.

@agerwick
Last active December 14, 2015 22:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agerwick/5158730 to your computer and use it in GitHub Desktop.
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 .
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