Skip to content

@headius /gist:2516338
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Add queue support to WeakRef
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:
@headius
Owner

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.