| 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)
Create a new WeakRef from orig.
# File lib/weakref.rb, line 49
49: def initialize(orig)
50: super
51: @__id = orig.__id__
52: ObjectSpace.define_finalizer orig, @@final
53: ObjectSpace.define_finalizer self, @@final
54: __old_status = Thread.critical
55: begin
56: Thread.critical = true
57: @@id_map[@__id] = [] unless @@id_map[@__id]
58: ensure
59: Thread.critical = __old_status
60: end
61: @@id_map[@__id].push self.__id__
62: @@id_rev_map[self.__id__] = @__id
63: end
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 68
68: def __getobj__
69: unless @@id_rev_map[self.__id__] == @__id
70: raise RefError, "Illegal Reference - probably recycled", caller(2)
71: end
72: begin
73: ObjectSpace._id2ref(@__id)
74: rescue RangeError
75: raise RefError, "Illegal Reference - probably recycled", caller(2)
76: end
77: end