Commit 7caeba1
committed
Define DelegateClass methods in separate module
Before this commit, modules included in a `DelegateClass` could not
override delegate methods:
```ruby
Base = Class.new do
def foo
"base"
end
end
Helper = Module.new do
def foo
"helper"
end
end
WithHelper = DelegateClass(Base) { include Helper }
WithHelper.new(Base.new).foo
# => "base"
```
This commit defines delegate methods in a separate module, so other
modules can come before it in the method lookup chain:
```ruby
WithHelper.new(Base.new).foo
# => "helper"
```
Also, because of this change, methods in a `DelegateClass` block will
properly override instead of redefine. Therefore, calling `super` is
faster:
**Benchmark script**
```ruby
# frozen_string_literal: true
require "benchmark/ips"
$LOAD_PATH.prepend(".../delegate/lib")
require "delegate"
Base = Class.new do
def foo
end
end
Overridden = DelegateClass(Base) do
def foo
super
end
end
overridden = Overridden.new(Base.new)
Benchmark.ips do |x|
x.report("super") { overridden.foo }
end
```
**Before**
```
Warming up --------------------------------------
super 75.044k i/100ms
Calculating -------------------------------------
super 759.506k (± 0.8%) i/s - 3.827M in 5.039488s
```
**After**
```
Warming up --------------------------------------
super 184.164k i/100ms
Calculating -------------------------------------
super 1.835M (± 1.0%) i/s - 9.208M in 5.019711s
```
Fixes https://bugs.ruby-lang.org/issues/19079.1 parent 5a19c23 commit 7caeba1
2 files changed
Lines changed: 13 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
410 | 410 | | |
411 | 411 | | |
412 | 412 | | |
| 413 | + | |
| 414 | + | |
413 | 415 | | |
414 | 416 | | |
415 | | - | |
416 | 417 | | |
417 | 418 | | |
418 | 419 | | |
419 | 420 | | |
420 | | - | |
421 | 421 | | |
422 | | - | |
| 422 | + | |
423 | 423 | | |
424 | 424 | | |
425 | 425 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
41 | 41 | | |
42 | 42 | | |
43 | 43 | | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
44 | 54 | | |
45 | 55 | | |
46 | 56 | | |
| |||
0 commit comments