Skip to content

Commit 0c4848b

Browse files
committed
Document Class.descendants advice
1 parent ed60d2b commit 0c4848b

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

STYLEGUIDE.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1096,4 +1096,24 @@ If you need to call a subview that expects an instance variable be set. If possi
10961096

10971097
Unfortunately the only way to get data into a layout template is with instance variables. You can't explicitly pass locals to them.
10981098

1099+
1100+
### Avoid `Class#descendants` and `Class#subclasses`
1101+
1102+
Avoid using `Class#descendants` and `Class#subclasses` as they are unreliable for several reasons:
1103+
1104+
* They don't know about classes that haven't been autoloaded yet
1105+
* 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.
1106+
1107+
```ruby
1108+
# bad
1109+
class Person < ApplicationRecord
1110+
end
1111+
1112+
class Employee < Person
1113+
end
1114+
1115+
Person.descendants # => Unreliable, may or may not include Employee
1116+
Person.subclasses # => Unreliable, may or may not include Employee
1117+
```
1118+
10991119
[rubocop-guide]: https://github.com/rubocop-hq/ruby-style-guide

0 commit comments

Comments
 (0)