Skip to content

Instantly share code, notes, and snippets.

@headius
Created April 28, 2012 05:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save headius/2516417 to your computer and use it in GitHub Desktop.
Save headius/2516417 to your computer and use it in GitHub Desktop.
Non-delegate WeakRef implementation
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