From 60610031009e60bdfe5775b0316df251ee36a973 Mon Sep 17 00:00:00 2001 From: Jonathan Hefner Date: Tue, 11 Oct 2022 12:02:15 -0500 Subject: [PATCH] [ruby/delegate] Fix DelegateClass block "method redefined" warning This commit prevents "method redefined" warnings when overriding methods within a `DelegateClass` block, such as in the following example: ```ruby Base = Class.new do def foo "foo" end end Overridden = DelegateClass(Base) do def foo super + "!" end end ``` Fixes https://bugs.ruby-lang.org/issues/19047. https://github.com/ruby/delegate/commit/214fae86de --- lib/delegate.rb | 2 ++ test/test_delegate.rb | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/lib/delegate.rb b/lib/delegate.rb index 70d4e4ad1d..af95c866f3 100644 --- a/lib/delegate.rb +++ b/lib/delegate.rb @@ -412,10 +412,12 @@ def DelegateClass(superclass, &block) end protected_instance_methods.each do |method| define_method(method, Delegator.delegating_block(method)) + alias_method(method, method) protected method end public_instance_methods.each do |method| define_method(method, Delegator.delegating_block(method)) + alias_method(method, method) end end klass.define_singleton_method :public_instance_methods do |all=true| diff --git a/test/test_delegate.rb b/test/test_delegate.rb index 57480b18ea..431d134f0f 100644 --- a/test/test_delegate.rb +++ b/test/test_delegate.rb @@ -29,6 +29,18 @@ class TestDelegateClass < Test::Unit::TestCase assert_equal(1, klass.new([1]).foo) end + def test_delegate_class_block_with_override + warning = EnvUtil.verbose_warning do + klass = DelegateClass(Array) do + def first + super.inspect + end + end + assert_equal("1", klass.new([1]).first) + end + assert_empty(warning) + end + def test_systemcallerror_eq e = SystemCallError.new(0) assert((SimpleDelegator.new(e) == e) == (e == SimpleDelegator.new(e)), "[ruby-dev:34808]")