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


@zverok Absolutely, the API of a dynamic language should be dynamic.

For example, take this:

```ruby
C = Class.new
Object.subclasses # (1)

D = Class.new
Object.subclasses # (2)
```

For the user, it makes sense that (1) includes `C`, and (2) includes `C` and `D`. They are guaranteed to be there, because `Object` has a strong reference to them via its constants table, and this fact belongs to the public API of Ruby. (My points are not about constants, but in that example, in order to say that (2) has `C` and `D` I need to say there's a strong reference somewhere.)

If you later on add a mixin:

```ruby
C.include(M)
```

of course, `C.ancestors` is supposed to reflect that change.

What would be strange is that

```ruby
C.ancestors
C.ancestors
```

could yield different results if you did not change the ancestor chain in between.

That is, you didn't do anything to change that collection.

> but is this difference practicalor only affects "theoretical clarity"

It's not marble tower theoretical clarity, it is just that the API of the language has to agree with the language model.

There are APIs that conceptually are about live objects, like `ObjectSpace`. But `Class#subclasses` is not at that level, conceptually. `Class#subclasses` is at the level of `Module#ancestors`, in my view.

> I assume that as a developer of the Zeitwerk you maybe can provide some insight on practical consequences?

In my view, the API introduces a broken window, a method that behaves in a non-deterministic way. Broken windows leak.



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

* 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>