From aa430d9ae021a31322d7cbaa012578afb9ff80a8 Mon Sep 17 00:00:00 2001 From: Caleb Thompson Date: Tue, 9 Jul 2013 14:33:59 -0400 Subject: [PATCH] Add examples for SimpleDelegator MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SimpleDelegator’s documentation lacked an example of its primary feature, that it automatically sets the object passed to its initializer as the delegated object. * Add implicit __setobj__ example * Add example showing that super is available as a shortcut to __getobj__. --- lib/delegate.rb | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/lib/delegate.rb b/lib/delegate.rb index e46e4f8..a2ca46f 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. # -- 1.8.2.3