public
Created

Non-delegate WeakRef implementation

  • Download Gist
gistfile1.diff
Diff
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
diff --git a/lib/weakref.rb b/lib/weakref.rb
index 78f88a3..7129873 100644
--- a/lib/weakref.rb
+++ b/lib/weakref.rb
@@ -54,6 +54,37 @@ class WeakRef < Delegator
end
end
+module GC
+
+ # New WeakRef that is not a delegate.
+ # The referenced object can be retrieved with
+ # +get+ and the reference can be cleared with
+ # +clear+, but otherwise no modification is
+ # supported.
+ class WeakRef
+ @@__map = ::ObjectSpace::WeakMap.new
+
+ ##
+ # Creates a weak reference to +orig+
+
+ def initialize(orig)
+ @@__map[self] = orig
+ end
+
+ ##
+ # Get the object referenced by this WeakRef. If the
+ # object has been collected, this will return nil.
+
+ def get # :nodoc:
+ @@__map[self]
+ end
+
+ def clear
+ @@__map[self] = nil
+ end
+ end
+end
+
if __FILE__ == $0
# require 'thread'
foo = Object.new

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.