Sha256: f2c85c39eb859cd22a899ab4fe07574575789b4683528d3c418b06ce961566c2

Contents?: true

Size: 1.15 KB

Versions: 1

Compression:

Stored size: 1.15 KB

Contents


module BBLib
  # Various methods for finding descendants and subclasses of a class. Intended as an
  # extend mixin for any class.
  module FamilyTree
    # Return all classes that inherit from this class
    def descendants(include_singletons = false)
      ObjectSpace.each_object(Class).select do |c|
        (include_singletons || !c.singleton_class?) && c < self
      end
    end

    alias subclasses descendants

    # Return all classes that directly inherit from this class
    def direct_descendants(include_singletons = false)
      ObjectSpace.each_object(Class).select do |c|
        (include_singletons || !c.singleton_class?) && c.ancestors[1] == self
      end
    end

    # Return all live instances of the class
    # Passing false will not include instances of sub classes
    def instances(descendants = true)
      inst = ObjectSpace.each_object(self).to_a
      descendants ? inst : inst.select { |i| i.class == self }
    end

    def namespace
      BBLib.namespace_of(self)
    end

    def root_namespace
      BBLib.root_namespace_of(self)
    end

    alias direct_subclasses direct_descendants

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
bblib-0.4.1 lib/mixins/family_tree.rb