Skip to content

Instantly share code, notes, and snippets.

@headius headius/gist:2516338
Created Apr 28, 2012

What would you like to do?
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
+ QUEUE_FINALIZER = ->(queue, weakref, id) do
+ queue.push(weakref)
+ end
@@__map =
# Creates a weak reference to +orig+
- def initialize(orig)
+ def initialize(orig, queue = nil)
case orig
when true, false, nil
@delegate_sd_obj = orig
@@__map[self] = orig
- super
+ if queue
+ finalizer = QUEUE_FINALIZER.curry[queue][self]
+ ObjectSpace.define_finalizer(orig, finalizer)
+ end
+ super(orig)
def __getobj__ # :nodoc:

This comment has been minimized.

Copy link
Owner Author

headius commented Apr 28, 2012

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
You can’t perform that action at this time.