public
Created

Add queue support to WeakRef

  • 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 43
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:

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.