Module: Corefines::Class::Descendants

Defined in:
lib/corefines/class.rb

Instance Method Summary collapse

Instance Method Details

#descendantsArray<Class>

Returns all descendants of this class.

Examples:

Integer.descendants  # => [Fixnum, Bignum]
Numeric.descendants  # => [Integer, Fixnum, Float, Bignum, Rational, Complex]

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/corefines/class.rb', line 13

module Descendants
  begin
    # Just try whether it raises exception...
    ::ObjectSpace.each_object(::Class.new) {}

    refine ::Class do
      def descendants
        descendants = []
        ::ObjectSpace.each_object(singleton_class) do |klass|
          descendants.unshift(klass) unless klass == self
        end
        descendants
      end
    end

  # Compatibility mode for JRuby when running without option -X+O.
  rescue StandardError

    refine ::Class do
      def descendants
        descendants = []
        ::ObjectSpace.each_object(::Class) do |klass|
          descendants.unshift(klass) if klass < self
        end
        descendants.uniq
      end
    end
  end
end