1 2 3 4 5 6 7 8 9 10 11 12 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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
# frozen_string_literal: true
require "concurrent/array"
module Dry
module Core
# An implementation of descendants tracker, heavily inspired
# by the descendants_tracker gem.
#
# @example
#
# class Base
# extend Dry::Core::DescendantsTracker
# end
#
# class A < Base
# end
#
# class B < Base
# end
#
# class C < A
# end
#
# Base.descendants # => [C, B, A]
# A.descendants # => [C]
# B.descendants # => []
#
module DescendantsTracker
class << self
# @api private
def setup(target)
target.instance_variable_set(:@descendants, Concurrent::Array.new)
end
private
# @api private
def extended(base)
super
DescendantsTracker.setup(base)
end
end
# Return the descendants of this class
#
# @example
# descendants = Parent.descendants
#
# @return [Array<Class>]
#
# @api public
attr_reader :descendants
protected
# @api private
def add_descendant(descendant)
ancestor = superclass
if ancestor.respond_to?(:add_descendant, true)
ancestor.add_descendant(descendant)
end
descendants.unshift(descendant)
end
private
# @api private
def inherited(descendant)
super
DescendantsTracker.setup(descendant)
add_descendant(descendant)
end
end
end
end
|