Skip to content

Commit d3ec14f

Browse files
committed
add .descendants and .subclasses advice
1 parent 86bffd4 commit d3ec14f

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

README.adoc

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -745,6 +745,25 @@ end
745745

746746
Check the https://github.com/norman/friendly_id[gem documentation] for more information about its usage.
747747

748+
=== Avoid `Class#descendants` and `Class#subclasses` [[avoid-class-descendants]]
749+
750+
Avoid using `Class#descendants` and `Class#subclasses` as they are unreliable for several reasons:
751+
752+
* They don't know about things that have yet to be autoloaded
753+
* They're non-deterministic with regards to Garbage Collection of classes. If you use `Class#descendants` or `Class#subclasses` in tests, where there is a pattern to dynamically define classes, GC is unpredictable for when those classes are cleaned up and removed by the GC.
754+
755+
[source,ruby]
756+
----
757+
# bad
758+
class Person < ApplicationRecord
759+
end
760+
761+
class Employee < Person
762+
end
763+
764+
Person.descendants # => Unreliable, may or may not include Employee
765+
----
766+
748767
=== `find_each` [[find-each]]
749768

750769
Use `find_each` to iterate over a collection of AR objects.

0 commit comments

Comments
 (0)