Class: Wref::Implementations::WeakRef

Inherits:
Object
  • Object
show all
Defined in:
lib/wref/implementations/weak_ref.rb

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ WeakRef

Returns a new instance of WeakRef.



2
3
4
5
6
7
8
# File 'lib/wref/implementations/weak_ref.rb', line 2

def initialize(object)
  require "weakref"
  @id = object.__id__
  @class_name = object.class.name.to_sym
  @weak_ref = ::WeakRef.new(object)
  ObjectSpace.define_finalizer(object, method(:destroy))
end

Instance Method Details

#alive?Boolean

Returns:

  • (Boolean)


38
39
40
41
42
43
44
# File 'lib/wref/implementations/weak_ref.rb', line 38

def alive?
  if @weak_ref.weakref_alive? && get
    return true
  else
    return false
  end
end

#getObject



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/wref/implementations/weak_ref.rb', line 10

def get
  return nil unless @id

  begin
    object = @weak_ref.__getobj__
  rescue WeakRef::RefError
    destroy
    return nil
  end

  object_class_name = object.class.name

  if !object_class_name || @class_name != object_class_name.to_sym || @id != object.__id__
    destroy
    return nil
  end

  return object
end

#get!Object



30
31
32
33
34
35
36
# File 'lib/wref/implementations/weak_ref.rb', line 30

def get!
  if object = get
    return object
  else
    raise Wref::Recycled
  end
end