Class: WeakRef

Inherits:
Delegator show all
Defined in:
lib/weakref.rb

Overview

Weak Reference class that allows a referenced object to be garbage-collected.

A WeakRef may be used exactly like the object it references.

Usage:

foo = Object.new            # create a new object instance
p foo.to_s                  # original's class
foo = WeakRef.new(foo)      # reassign foo with WeakRef instance
p foo.to_s                  # should be same class
GC.start                    # start the garbage collector
p foo.to_s                  # should raise exception (recycled)

Defined Under Namespace

Classes: RefError

Constant Summary collapse

VERSION =
"0.1.3"
@@__map =
::ObjectSpace::WeakMap.new

Instance Method Summary collapse

Methods inherited from Delegator

#!, #!=, #==, const_missing, delegating_block, #eql?, #freeze, #marshal_dump, #marshal_load, #methods, #protected_methods, public_api, #public_methods, #respond_to_missing?

Constructor Details

#initialize(orig) ⇒ WeakRef

Creates a weak reference to orig



34
35
36
37
38
39
40
41
42
# File 'lib/weakref.rb', line 34

def initialize(orig)
  case orig
  when true, false, nil
    @delegate_sd_obj = orig
  else
    @@__map[self] = orig
  end
  super
end

Instance Method Details

#__getobj__Object

:nodoc:



44
45
46
47
# File 'lib/weakref.rb', line 44

def __getobj__ # :nodoc:
  @@__map[self] or defined?(@delegate_sd_obj) ? @delegate_sd_obj :
    Kernel::raise(RefError, "Invalid Reference - probably recycled", Kernel::caller(2))
end

#__setobj__(obj) ⇒ Object

:nodoc:



49
50
# File 'lib/weakref.rb', line 49

def __setobj__(obj) # :nodoc:
end

#weakref_alive?Boolean

Returns true if the referenced object is still alive.

Returns:

  • (Boolean)


55
56
57
# File 'lib/weakref.rb', line 55

def weakref_alive?
  @@__map.key?(self) or defined?(@delegate_sd_obj)
end