summaryrefslogtreecommitdiff
path: root/lib/delegate.rb
diff options
context:
space:
mode:
authormatz <matz@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>1998-06-26 09:45:09 +0000
committermatz <matz@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>1998-06-26 09:45:09 +0000
commit05da25f297c4d26b6bb454a9649b1dd63a102910 (patch)
tree568d1118ca9c2c7bfbcaf2d2132a7e870367d407 /lib/delegate.rb
parent839f4c5f3fdb4ea6b270fce17f1c3881060087d4 (diff)
980626
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/v1_1r@255 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'lib/delegate.rb')
-rw-r--r--lib/delegate.rb46
1 files changed, 45 insertions, 1 deletions
diff --git a/lib/delegate.rb b/lib/delegate.rb
index 7889c8284f..925b4ec867 100644
--- a/lib/delegate.rb
+++ b/lib/delegate.rb
@@ -9,6 +9,12 @@
# foo = Object.new
# foo2 = SimpleDelegator.new(foo)
# foo.hash == foo2.hash # => true
+#
+# Foo = DelegateClass(Array)
+#
+# class ExtArray<DelegateClass(Array)
+# ...
+# end
class Delegator
@@ -18,7 +24,7 @@ class Delegator
preserved |= t.instance_methods
break if t == Delegator
end
- preserved -= ["__getobj__","to_s","nil?","to_a","hash","dup","==","=~"]
+ preserved -= ["__getobj__","to_s","to_a","inspect","hash","eql?","==","=~","==="]
for method in obj.methods
next if preserved.include? method
eval <<EOS
@@ -61,7 +67,44 @@ end
Delegater = Delegator
SimpleDelegater = SimpleDelegator
+#
+def DelegateClass(superclass)
+ klass = Class.new
+ methods = superclass.instance_methods
+ methods -= ::Kernel.instance_methods
+ methods |= ["to_s","to_a","inspect","hash","eql?","==","=~","==="]
+ klass.module_eval <<EOS
+ def initialize(obj)
+ @obj = obj
+ end
+EOS
+ for method in methods
+ klass.module_eval <<EOS
+ def #{method}(*args, &block)
+ begin
+ @obj.__send__(:#{method}, *args, &block)
+ rescue
+ $@[0,2] = nil
+ raise
+ end
+ end
+EOS
+ end
+ return klass;
+end
+
if __FILE__ == $0
+ class ExtArray<DelegateClass(Array)
+ def initialize()
+ super([])
+ end
+ end
+
+ ary = ExtArray.new
+ p ary.type
+ ary.push 25
+ p ary
+
foo = Object.new
def foo.test
raise 'this is OK'
@@ -69,4 +112,5 @@ if __FILE__ == $0
foo2 = SimpleDelegator.new(foo)
p foo.hash == foo2.hash # => true
foo.test # raise error!
+
end