Sha256: dac161addb85a84eed90d6fd13c32c3fb30f8dbd7145e8e28254415c223153e8

Contents?: true

Size: 1.16 KB

Versions: 10

Compression:

Stored size: 1.16 KB

Contents

# TITLE:
#
#   Class Descendent Extensions
#
# SUMMARY:
#
#   Extension methods for Class class for accessing
#   and even removing subclasses.
#
# CREDITS:
#
#   - ?

class Class

  def descendents
    subclass = []
    ObjectSpace.each_object( Class ) do |c|
      if c.ancestors.include?( self ) and self != c
        subclass << c
      end
    end
    return subclass
  end

  alias_method :subclasses, :descendents

  def remove_descendents
    self.descendents.each do |subclass|
      Object.send(:remove_const, subclass.name) rescue nil
    end
    ObjectSpace.garbage_collect
  end

  alias_method :remove_subclasses, :remove_descendents

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TestClassDescendents < Test::Unit::TestCase

    class A ; end
    class B < A ; end
    class C < B ; end

    def test_descendents
      assert_equal( [C,B], A.descendents )
    end

    def test_remove_descendents
      assert_nothing_raised { B.remove_descendents }
      # doesn't work despite above; not sure why
      #assert_equal( [B], A.descendents )
    end

  end

=end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
facets-2.0.1 lib/core/facets/class/descendents.rb
facets-2.0.0 lib/core/facets/class/descendents.rb
facets-2.0.2 lib/core/facets/class/descendents.rb
facets-2.0.5 lib/core/facets/class/descendents.rb
facets-2.1.1 lib/core/facets/class/descendents.rb
facets-2.1.2 lib/core/facets/class/descendents.rb
facets-2.0.4 lib/core/facets/class/descendents.rb
facets-2.1.0 lib/core/facets/class/descendents.rb
facets-2.0.3 lib/core/facets/class/descendents.rb
facets-2.1.3 lib/core/facets/class/descendents.rb