Skip to content

Commit

Permalink
Make def_*_delegator return name of method defined (Fixes #10)
Browse files Browse the repository at this point in the history
This restores compatibility with previous versions.  This behavior
was previously undefined, but it makes sense for the name of the
defined method to be returned.
  • Loading branch information
jeremyevans committed Dec 2, 2019
1 parent e56f0f8 commit a52ef34
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
8 changes: 6 additions & 2 deletions lib/forwardable.rb
Expand Up @@ -160,6 +160,7 @@ def def_instance_delegators(accessor, *methods)
# +accessor.method+. +accessor+ should be a method name, instance
# variable name, or constant name. Use the full path to the
# constant if providing the constant name.
# Returns the name of the method defined.
#
# class MyQueue
# CONST = 1
Expand All @@ -184,8 +185,9 @@ def def_instance_delegator(accessor, method, ali = method)

# If it's not a class or module, it's an instance
mod = Module === self ? self : singleton_class
mod.module_eval(&gen)
ret = mod.module_eval(&gen)
mod.send(:ruby2_keywords, ali) if RUBY_VERSION >= '2.7'
ret
end

alias delegate instance_delegate
Expand Down Expand Up @@ -299,11 +301,13 @@ def def_single_delegators(accessor, *methods)
# Defines a method _method_ which delegates to _accessor_ (i.e. it calls
# the method of the same name in _accessor_). If _new_name_ is
# provided, it is used as the name for the delegate method.
# Returns the name of the method defined.
def def_single_delegator(accessor, method, ali = method)
gen = Forwardable._delegator_method(self, accessor, method, ali)

instance_eval(&gen)
ret = instance_eval(&gen)
singleton_class.send(:ruby2_keywords, ali) if RUBY_VERSION >= '2.7'
ret
end

alias delegate single_delegate
Expand Down
8 changes: 6 additions & 2 deletions test/test_forwardable.rb
Expand Up @@ -24,11 +24,13 @@ def delegated1_kw(**kw)

def test_def_instance_delegator
%i[def_delegator def_instance_delegator].each do |m|
ret = nil
cls = forwardable_class do
__send__ m, :@receiver, :delegated1
ret = __send__ m, :@receiver, :delegated1
end

assert_same RETURNED1, cls.new.delegated1
assert_equal :delegated1, ret
end
end

Expand Down Expand Up @@ -185,11 +187,13 @@ def test_def_instance_delegate_using_block_method_as_receiver

def test_class_single_delegator
%i[def_delegator def_single_delegator].each do |m|
ret = nil
cls = single_forwardable_class do
__send__ m, :@receiver, :delegated1
ret = __send__ m, :@receiver, :delegated1
end

assert_same RETURNED1, cls.delegated1
assert_equal :delegated1, ret
end
end

Expand Down

0 comments on commit a52ef34

Please sign in to comment.