Class: Wref
- Inherits:
-
Object
- Object
- Wref
- Defined in:
- lib/wref.rb
Overview
A simple weak-reference framework with mapping. Only handles the referencing of objects.
Examples
user_obj = ob.get(:User, 1) weak_ref = Wref.new(user_obj) user_obj = nil sleep 0.5 GC.start
begin
user_obj = weak_ref.get
print "The user still exists in memory and has ID #{user.id}."
rescue Wref::Recycled
print "The user has been removed from memory."
end
Defined Under Namespace
Classes: Implementations, Map, Recycled
Instance Attribute Summary collapse
-
#implementation ⇒ Object
readonly
Returns the value of attribute implementation.
-
#weak_ref ⇒ Object
readonly
Returns the value of attribute weak_ref.
Instance Method Summary collapse
-
#alive? ⇒ Boolean
(also: #weakref_alive?)
Returns true if the reference is still alive.
-
#get ⇒ Object
(also: #__getobj__)
The same as the normal ‘get!’ but returns nil instead of raising Wref::Cycled-error.
-
#get! ⇒ Object
Returns the object that this weak reference holds or raises Wref::Recycled.
-
#initialize(object, impl: nil) ⇒ Wref
constructor
Initializes various variables.
Constructor Details
#initialize(object, impl: nil) ⇒ Wref
Initializes various variables.
36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/wref.rb', line 36 def initialize(object, impl: nil) if impl @implementation = impl elsif RUBY_ENGINE == "jruby" @implementation = :JavaWeakReference else @implementation = :IdClassUnique end @weak_ref = Wref::Implementations.const_get(implementation).new(object) end |
Instance Attribute Details
#implementation ⇒ Object (readonly)
Returns the value of attribute implementation.
33 34 35 |
# File 'lib/wref.rb', line 33 def implementation @implementation end |
#weak_ref ⇒ Object (readonly)
Returns the value of attribute weak_ref.
33 34 35 |
# File 'lib/wref.rb', line 33 def weak_ref @weak_ref end |
Instance Method Details
#alive? ⇒ Boolean Also known as: weakref_alive?
Returns true if the reference is still alive. print “The object still exists in memory.” if wref.alive?
66 67 68 |
# File 'lib/wref.rb', line 66 def alive? @weak_ref.alive? end |
#get ⇒ Object Also known as: __getobj__
The same as the normal ‘get!’ but returns nil instead of raising Wref::Cycled-error.
60 61 62 |
# File 'lib/wref.rb', line 60 def get @weak_ref.get end |
#get! ⇒ Object
Returns the object that this weak reference holds or raises Wref::Recycled. begin
object = wref.get!
puts "Object still exists in memory."
rescue Wref::Recycled
puts "Object has been garbage-collected."
end
55 56 57 |
# File 'lib/wref.rb', line 55 def get! @weak_ref.get! end |