| Class | WeakRef |
| In: |
lib/weakref.rb
|
| Parent: | Delegator |
WeakRef is a class to represent a reference to an object that is not seen by the tracing phase of the garbage collector. This allows the referenced object to be garbage collected as if nothing is referring to it. Because WeakRef delegates method calls to the referenced object, it may be used in place of that object, i.e. it is of the same duck type.
Usage:
foo = Object.new foo = Object.new p foo.to_s # original's class foo = WeakRef.new(foo) p foo.to_s # should be same class ObjectSpace.garbage_collect p foo.to_s # should raise exception (recycled)
Return the object this WeakRef references. Raises RefError if the object has been garbage collected. The object returned is the object to which method calls are delegated (see Delegator).
# File lib/weakref.rb, line 57
57: def __getobj__
58: unless @@id_rev_map[self.__id__] == @__id
59: raise RefError, "Illegal Reference - probably recycled", caller(2)
60: end
61: begin
62: ObjectSpace._id2ref(@__id)
63: rescue RangeError
64: raise RefError, "Illegal Reference - probably recycled", caller(2)
65: end
66: end
# File lib/weakref.rb, line 68
68: def __setobj__(obj)
69: @__id = obj.__id__
70: __old_status = Thread.critical
71: begin
72: Thread.critical = true
73: unless @@id_rev_map.key?(self)
74: ObjectSpace.define_finalizer obj, @@final
75: ObjectSpace.define_finalizer self, @@final
76: end
77: @@id_map[@__id] = [] unless @@id_map[@__id]
78: ensure
79: Thread.critical = __old_status
80: end
81: @@id_map[@__id].push self.__id__
82: @@id_rev_map[self.__id__] = @__id
83: end