Issue #18273 has been updated by fxn (Xavier Noria).


In my view, this method does not play well with object lifetime, semantically.

Take for example:

```ruby
C = Class.new
-> { Class.new(C); 1 }.call
pp C.subclasses # => [#<Class:0x000000010c8f5a90>]
```

On line 3, the subclass of `C` does not exist anymore conceptually, but `Class#subclasses` depends on GC actually deleting the object. That is non-deterministic behaviour.

This affects reloading in Zeitwerk, which is implemented via `remove_const`. If the program using Zeitwerk is correct, after `remove_const` there are no strong references to the unloaded object. But if you define a subclass again on reload, `C#subclasses` may yield two objects instead of one.

----------------------------------------
Feature #18273: Class#subclasses
https://bugs.ruby-lang.org/issues/18273#change-96106

* Author: byroot (Jean Boussier)
* Status: Closed
* Priority: Normal
----------------------------------------
Ref: https://github.com/rails/rails/pull/43481

Something we forgot to mention in [Feature #14394], is either a parameter or another method to only get direct descendants.

Active Support has been offering `Class.subclasses` as:

```ruby
  def subclasses
    descendants.select { |descendant| descendant.superclass == self }
  end
```

It seems a bit silly to grab all descendants and then restrict the list when `Class#descendants` had to do some recursion to get them all in the first place.

### Proposal

We could either implement `Class#subclasses` directly, or accept a parameter in `Class#descendants`, e.g. `descendants(immediate = false)`.

cc @eregon



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>