From 0357488b439b37922171ad72cc7839736ff757a3 Mon Sep 17 00:00:00 2001 From: zzak Date: Wed, 10 Jul 2013 15:50:23 +0000 Subject: [PATCH] * lib/delegate.rb: Add example for __setobj__ and __getobj__ [Bug #8615] Patch by Caleb Thompson git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@41905 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ lib/delegate.rb | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/ChangeLog b/ChangeLog index 0faa27ed2e..8b763dac3e 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Thu Jul 11 00:48:29 2013 Zachary Scott + + * lib/delegate.rb: Add example for __setobj__ and __getobj__ + [Bug #8615] Patch by Caleb Thompson + Wed Jul 10 23:29:22 2013 Zachary Scott * lib/logger.rb: Use :call-seq: for method signature rdoc diff --git a/lib/delegate.rb b/lib/delegate.rb index e46e4f8c23..a2ca46fafa 100644 --- a/lib/delegate.rb +++ b/lib/delegate.rb @@ -230,6 +230,34 @@ end # and even to change the object being delegated to at a later time with # #__setobj__. # +# class User +# def born_on +# Date.new(1989, 09, 10) +# end +# end +# +# class UserDecorator < SimpleDelegator +# def birth_year +# born_on.year +# end +# end +# +# decorated_user = UserDecorator.new(User.new) +# decorated_user.birth_year #=> 1989 +# decorated_user.__getobj__ #=> # +# +# A SimpleDelegator instance can take advantage of the fact that SimpleDelegator +# is a subclass of +Delegator+ to call super to have methods called on +# the object being delegated to. +# +# class SuperArray < SimpleDelegator +# def [](*args) +# super + 1 +# end +# end +# +# SuperArray.new([1])[0] #=> 2 +# # Here's a simple example that takes advantage of the fact that # SimpleDelegator's delegation object can be changed at any time. #