Skip to content

Instantly share code, notes, and snippets.

@hawx
Created February 12, 2015 18:26
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 hawx/b254d7d26f79ddec78a0 to your computer and use it in GitHub Desktop.
Save hawx/b254d7d26f79ddec78a0 to your computer and use it in GitHub Desktop.
adds Object#subclasses
class Object
# A method that adds a #subclass class method allowing
# you to find the subclasses of a particular class.
#
# @example
#
# class String2 < String; end
# class String3 < String; end
# String.subclasses
# #=> [:String2, :String3]
#
# class String2Sub < String2; end
# String2.subclasses
# #=> [:String2Sub]
# String.subclasses
# #=> [:String2, :String3, :String2Sub]
#
# @return [Array[Symbol]]
#
def self.subclasses
Module.constants.find_all do |c_klass|
if c_klass != c_klass.upcase
self > (Object.const_get(c_klass))
else
nil
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment