Created
April 28, 2012 05:41
-
-
Save headius/2516338 to your computer and use it in GitHub Desktop.
Add queue support to WeakRef
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..fb0a274 100644 | |
--- a/lib/weakref.rb | |
+++ b/lib/weakref.rb | |
@@ -1,4 +1,5 @@ | |
require "delegate" | |
+require "thread" | |
# Weak Reference class that allows a referenced object to be | |
# garbage-collected. A WeakRef may be used exactly like the object it | |
@@ -22,20 +23,30 @@ class WeakRef < Delegator | |
class RefError < StandardError | |
end | |
+ | |
+ QUEUE_FINALIZER = ->(queue, weakref, id) do | |
+ queue.push(weakref) | |
+ end | |
@@__map = ::ObjectSpace::WeakMap.new | |
## | |
# Creates a weak reference to +orig+ | |
- def initialize(orig) | |
+ def initialize(orig, queue = nil) | |
case orig | |
when true, false, nil | |
@delegate_sd_obj = orig | |
else | |
@@__map[self] = orig | |
end | |
- super | |
+ | |
+ if queue | |
+ finalizer = QUEUE_FINALIZER.curry[queue][self] | |
+ ObjectSpace.define_finalizer(orig, finalizer) | |
+ end | |
+ | |
+ super(orig) | |
end | |
def __getobj__ # :nodoc: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Actually I recognize that the require 'thread' is unnecessary here; all this patch requires is that you give it a Queue-like object with a "push" method.