2017-01-26 10:14:00 -05:00
|
|
|
# frozen_string_literal: true
|
2011-06-29 20:37:00 -04:00
|
|
|
require "delegate"
|
|
|
|
|
2011-08-26 18:22:37 -04:00
|
|
|
# Weak Reference class that allows a referenced object to be
|
2012-12-02 02:48:42 -05:00
|
|
|
# garbage-collected.
|
|
|
|
#
|
|
|
|
# A WeakRef may be used exactly like the object it references.
|
1998-01-16 07:19:09 -05:00
|
|
|
#
|
|
|
|
# Usage:
|
2011-06-29 20:37:00 -04:00
|
|
|
#
|
2012-12-02 02:48:42 -05:00
|
|
|
# foo = Object.new # create a new object instance
|
2011-05-18 20:07:25 -04:00
|
|
|
# p foo.to_s # original's class
|
2012-12-02 02:48:42 -05:00
|
|
|
# foo = WeakRef.new(foo) # reassign foo with WeakRef instance
|
2011-05-18 20:07:25 -04:00
|
|
|
# p foo.to_s # should be same class
|
2012-12-02 02:48:42 -05:00
|
|
|
# GC.start # start the garbage collector
|
2011-05-18 20:07:25 -04:00
|
|
|
# p foo.to_s # should raise exception (recycled)
|
2012-12-02 02:48:42 -05:00
|
|
|
#
|
1998-01-16 07:19:09 -05:00
|
|
|
|
2006-12-31 10:02:22 -05:00
|
|
|
class WeakRef < Delegator
|
2020-12-22 07:43:30 -05:00
|
|
|
VERSION = "0.1.1"
|
2006-12-31 10:02:22 -05:00
|
|
|
|
2011-06-29 20:37:00 -04:00
|
|
|
##
|
|
|
|
# RefError is raised when a referenced object has been recycled by the
|
|
|
|
# garbage collector
|
|
|
|
|
2006-12-31 10:02:22 -05:00
|
|
|
class RefError < StandardError
|
1999-01-19 23:59:39 -05:00
|
|
|
end
|
1998-01-16 07:19:09 -05:00
|
|
|
|
2012-03-12 23:37:06 -04:00
|
|
|
@@__map = ::ObjectSpace::WeakMap.new
|
1999-08-13 01:45:20 -04:00
|
|
|
|
2011-06-29 20:37:00 -04:00
|
|
|
##
|
|
|
|
# Creates a weak reference to +orig+
|
|
|
|
|
1998-01-16 07:19:09 -05:00
|
|
|
def initialize(orig)
|
2012-03-12 23:37:06 -04:00
|
|
|
case orig
|
|
|
|
when true, false, nil
|
|
|
|
@delegate_sd_obj = orig
|
|
|
|
else
|
|
|
|
@@__map[self] = orig
|
|
|
|
end
|
2005-08-12 03:17:36 -04:00
|
|
|
super
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
|
|
|
|
2011-06-29 20:37:00 -04:00
|
|
|
def __getobj__ # :nodoc:
|
2012-03-12 23:37:06 -04:00
|
|
|
@@__map[self] or defined?(@delegate_sd_obj) ? @delegate_sd_obj :
|
|
|
|
Kernel::raise(RefError, "Invalid Reference - probably recycled", Kernel::caller(2))
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
2011-06-29 20:37:00 -04:00
|
|
|
|
|
|
|
def __setobj__(obj) # :nodoc:
|
2005-08-12 03:17:36 -04:00
|
|
|
end
|
1998-01-16 07:19:09 -05:00
|
|
|
|
2011-06-29 20:37:00 -04:00
|
|
|
##
|
|
|
|
# Returns true if the referenced object is still alive.
|
|
|
|
|
1998-01-16 07:19:09 -05:00
|
|
|
def weakref_alive?
|
2013-10-18 02:59:12 -04:00
|
|
|
@@__map.key?(self) or defined?(@delegate_sd_obj)
|
1998-01-16 07:19:09 -05:00
|
|
|
end
|
|
|
|
end
|