summaryrefslogtreecommitdiff
path: root/lib/delegate.rb
diff options
context:
space:
mode:
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