Class: Knj::Wref

Inherits:
Object show all
Defined in:
lib/knj/wref.rb

Overview

A weak-reference that wont bite you in the ass like the one in Ruby 1.9.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj) ⇒ Wref

Returns a new instance of Wref.



21
22
23
24
25
# File 'lib/knj/wref.rb', line 21

def initialize(obj)
  @weakref = WeakRef.new(obj)
  @class_name = obj.class.name.to_sym
  @id = obj.__id__
end

Instance Attribute Details

#class_nameObject (readonly)

Returns the value of attribute class_name.



5
6
7
# File 'lib/knj/wref.rb', line 5

def class_name
  @class_name
end

#idObject (readonly)

Returns the value of attribute id.



5
6
7
# File 'lib/knj/wref.rb', line 5

def id
  @id
end

#mapObject (readonly)

Returns the value of attribute map.



5
6
7
# File 'lib/knj/wref.rb', line 5

def map
  @map
end

#map_idObject (readonly)

Returns the value of attribute map_id.



5
6
7
# File 'lib/knj/wref.rb', line 5

def map_id
  @map_id
end

#spawnedObject (readonly)

Returns the value of attribute spawned.



5
6
7
# File 'lib/knj/wref.rb', line 5

def spawned
  @spawned
end

Class Method Details

.debug_wrefsObject

Yields debug-output for every weak-ref that is alive.



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/knj/wref.rb', line 8

def self.debug_wrefs
  ObjectSpace.each_object(Knj::Wref) do |wref|
    begin
      obj = wref.get
    rescue WeakRef::RefError
      yield("str" => "Dead wref: #{wref.class_name} (#{wref.id})", "alive" => false, "wref" => wref)
      next
    end
    
    yield("str" => "Alive wref: #{wref.class_name} (#{wref.id})", "alive" => true, "wref" => wref, "obj" => obj)
  end
end

Instance Method Details

#alive?Boolean Also known as: weakref_alive?

Returns true if the reference is still alive.

Returns:

  • (Boolean)


40
41
42
43
44
45
46
47
# File 'lib/knj/wref.rb', line 40

def alive?
  begin
    self.get
    return true
  rescue WeakRef::RefError
    return false
  end
end

#destroyObject

Removes all data from this object.



50
51
52
53
54
# File 'lib/knj/wref.rb', line 50

def destroy
  @weakref = nil
  @class_name = nil
  @id = nil
end

#getObject Also known as: __getobj__

Returns the object that this weak reference holds or throws WeakRef::RefError.



28
29
30
31
32
33
34
35
36
37
# File 'lib/knj/wref.rb', line 28

def get
  obj = @weakref.__getobj__ if @weakref
  
  if !@weakref or @class_name != obj.class.name.to_sym or @id != obj.__id__
    self.destroy
    raise WeakRef::RefError
  end
  
  return obj
end