Skip to content

Commit

Permalink
Use Class#subclasses for DescendantTracker
Browse files Browse the repository at this point in the history
  • Loading branch information
flash-gordon committed Jan 10, 2022
1 parent 54c734a commit 63976da
Showing 1 changed file with 51 additions and 36 deletions.
87 changes: 51 additions & 36 deletions lib/dry/core/descendants_tracker.rb
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
# frozen_string_literal: true

require "concurrent/array"

module Dry
module Core
# An implementation of descendants tracker, heavily inspired
Expand All @@ -27,51 +25,68 @@ module Core
# B.descendants # => []
#
module DescendantsTracker
class << self
# @api private
def setup(target)
target.instance_variable_set(:@descendants, Concurrent::Array.new)
end
if RUBY_VERSION < "3.1"
require "concurrent/array"

private
class << self
# @api private
def setup(target)
target.instance_variable_set(:@descendants, Concurrent::Array.new)
end

# @api private
def extended(base)
super
private

DescendantsTracker.setup(base)
# @api private
def extended(base)
super

DescendantsTracker.setup(base)
end
end
end

# Return the descendants of this class
#
# @example
# descendants = Parent.descendants
#
# @return [Array<Class>]
#
# @api public
attr_reader :descendants
# Return the descendants of this class
#
# @example
# descendants = Parent.descendants
#
# @return [Array<Class>]
#
# @api public
attr_reader :descendants

protected
protected

# @api private
def add_descendant(descendant)
ancestor = superclass
if ancestor.respond_to?(:add_descendant, true)
ancestor.add_descendant(descendant)
# @api private
def add_descendant(descendant)
ancestor = superclass
if ancestor.respond_to?(:add_descendant, true)
ancestor.add_descendant(descendant)
end
descendants.push(descendant)
end
descendants.push(descendant)
end

private
private

# @api private
def inherited(descendant)
super

# @api private
def inherited(descendant)
super
DescendantsTracker.setup(descendant)
add_descendant(descendant)
end
else

DescendantsTracker.setup(descendant)
add_descendant(descendant)
# Return the descendants of this class
#
# @example
# descendants = Parent.descendants
#
# @return [Array<Class>]
#
# @api public
def descendants
subclasses.concat(subclasses.flat_map(&:subclasses))
end
end
end
end
Expand Down

0 comments on commit 63976da

Please sign in to comment.