Created
April 28, 2012 05:57
-
-
Save headius/2516417 to your computer and use it in GitHub Desktop.
Non-delegate WeakRef implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment