Sha256: 4f73846fd75a6accd2d33545e351b3e93dd789883bc644a46f63aa8d2a02ccfa

Contents?: true

Size: 940 Bytes

Versions: 5

Compression:

Stored size: 940 Bytes

Contents

module Reflexive
  module_function
  
  # List all descedents of this class.
  #
  #   class X ; end
  #   class A < X; end
  #   class B < X; end
  #   X.descendents  #=> [A,B]
  #
  # You may also limit the generational distance
  # the subclass may be from the parent class.
  #
  #   class X ; end
  #   class A < X; end
  #   class B < A; end
  #   X.descendents    #=> [A, B]
  #   X.descendents(1) #=> [A]
  #
  # NOTE: This is a intensive operation. Do not
  # expect it to be super fast.

  def descendants(klass, generations=nil)
    subclass = []
    
    ObjectSpace.each_object(Class) do |c|
      next if c == klass
      
      ancestors = c.ancestors[0 .. (generations || -1)]
      subclass << c if ancestors.include?(klass)

      ancestors = c.singleton_class.ancestors[0 .. (generations || -1)]
      subclass << c if ancestors.include?(klass)
    end
    
    subclass
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
reflexive-0.0.5 lib/reflexive/descendants.rb
reflexive-0.0.4 lib/reflexive/descendants.rb
reflexive-0.0.3 lib/reflexive/descendants.rb
reflexive-0.0.2 lib/reflexive/descendants.rb
reflexive-0.0.1 lib/reflexive/descendants.rb