Module: Eco::Language::Klass::Hierarchy

Included in:
AutoLoader, HelpersBuilt
Defined in:
lib/eco/language/klass/hierarchy.rb

Instance Method Summary collapse

Instance Method Details

#descendants(parent_class: self, direct: false, scope: nil) ⇒ Arrary<Class>

Note:

in native ruby, you might want #subclasses method.

Finds all child classes of the current class.

Parameters:

  • parent_class (Class) (defaults to: self)

    the parent class we want to find children of.

  • direct (Boolean) (defaults to: false)

    it will only include direct child classes.

  • scope (nil, Array) (defaults to: nil)

    to only look for descendants among the ones in scope.

Returns:

  • (Arrary<Class>)

    the child classes in hierarchy order.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/eco/language/klass/hierarchy.rb', line 9

def descendants(parent_class: self, direct: false, scope: nil)
  scope ||= ObjectSpace.each_object(::Class)
  return [] if scope.empty?

  scope.select do |klass|
    klass < parent_class
  end.sort do |k_1, k_2|
    next -1 if k_2 < k_1
    next  1 if k_1 < k_2
    0
  end.tap do |siblings|
    next unless direct

    siblings.reject! do |si|
      siblings.any? {|s| si < s}
    end
  end
end

#descendants?(parent_class: self, direct: false) ⇒ Boolean

Returns true if the current class has child classes, and false otherwise.

Parameters:

  • parent_class (Class) (defaults to: self)

    the parent class we want to find children of.

  • direct (Boolean) (defaults to: false)

    it will only include direct child classes.

Returns:

  • (Boolean)

    true if the current class has child classes, and false otherwise.



31
32
33
34
35
36
# File 'lib/eco/language/klass/hierarchy.rb', line 31

def descendants?(parent_class: self, direct: false)
  descendants(
    parent_class: parent_class,
    direct:       direct
  ).length.positive?
end