Skip to content

Commit

Permalink
Allow DelegateClass() to module_eval given block
Browse files Browse the repository at this point in the history
Methods that return classes often module_eval the given block
(e.g. Class.new and Struct.new).  This allows DelegateClass to
work similarly.  This makes it easier to use DelegateClass
directly without subclassing, so as not to create an unnecessary
subclass.

Implements [Feature #15842]
  • Loading branch information
jeremyevans committed May 31, 2019
1 parent 856593c commit 1cd93f1
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
5 changes: 5 additions & 0 deletions NEWS
Expand Up @@ -118,6 +118,11 @@ Date::
new Japanese era as an informal extension, until the new JIS X 0301 is
issued. [Feature #15742]

Delegate::

* Object#DelegateClass accepts a block and module_evals it in the context
of the returned class, similar to Class.new and Struct.new.

ERB::

* Prohibit marshaling ERB instance.
Expand Down
11 changes: 10 additions & 1 deletion lib/delegate.rb
Expand Up @@ -360,6 +360,14 @@ def Delegator.delegating_block(mid) # :nodoc:
# end
# end
#
# or:
#
# MyClass = DelegateClass(ClassToDelegateTo) do # Step 1
# def initialize
# super(obj_of_ClassToDelegateTo) # Step 2
# end
# end
#
# Here's a sample of use from Tempfile which is really a File object with a
# few special rules about storage location and when the File should be
# deleted. That makes for an almost textbook perfect example of how to use
Expand All @@ -383,7 +391,7 @@ def Delegator.delegating_block(mid) # :nodoc:
# # ...
# end
#
def DelegateClass(superclass)
def DelegateClass(superclass, &block)
klass = Class.new(Delegator)
methods = superclass.instance_methods
methods -= ::Delegator.public_api
Expand All @@ -410,5 +418,6 @@ def __setobj__(obj) # :nodoc:
klass.define_singleton_method :protected_instance_methods do |all=true|
super(all) | superclass.protected_instance_methods
end
klass.module_eval(&block) if block
return klass
end
7 changes: 7 additions & 0 deletions test/test_delegate.rb
Expand Up @@ -22,6 +22,13 @@ def test_extend
assert_equal(:m, obj.m, "[ruby-dev:33116]")
end

def test_delegate_class_block
klass = DelegateClass(Array) do
alias foo first
end
assert_equal(1, klass.new([1]).foo)
end

def test_systemcallerror_eq
e = SystemCallError.new(0)
assert((SimpleDelegator.new(e) == e) == (e == SimpleDelegator.new(e)), "[ruby-dev:34808]")
Expand Down

0 comments on commit 1cd93f1

Please sign in to comment.