Skip to content

Instantly share code, notes, and snippets.

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