Class: Knj::Wref_map
Instance Method Summary collapse
-
#clean ⇒ Object
Scans the whole map and removes dead references.
-
#destroy ⇒ Object
Unsets everything to free up memory.
-
#get(id) ⇒ Object
(also: #[])
Returns a object by ID or raises a RefError.
-
#get!(id) ⇒ Object
The same as ‘get’ but returns nil instead of WeakRef-error.
-
#initialize(args = {}) ⇒ Wref_map
constructor
A new instance of Wref_map.
-
#key?(key) ⇒ Boolean
(also: #has_key?)
Make it hash-compatible.
-
#set(id, obj) ⇒ Object
(also: #[]=)
Sets a new object in the map with a given ID.
-
#valid?(key) ⇒ Boolean
Returns true if a given key exists and the object it holds is alive.
Constructor Details
#initialize(args = {}) ⇒ Wref_map
Returns a new instance of Wref_map.
62 63 64 65 |
# File 'lib/knj/wref.rb', line 62 def initialize(args = {}) @args = args @map = {} end |
Instance Method Details
#clean ⇒ Object
Scans the whole map and removes dead references.
117 118 119 120 121 122 123 124 125 126 127 |
# File 'lib/knj/wref.rb', line 117 def clean @map.keys.each do |key| begin self.get(key) #this will remove the key if the object no longer exists. rescue WeakRef::RefError #ignore. end end return nil end |
#destroy ⇒ Object
Unsets everything to free up memory.
68 69 70 71 72 |
# File 'lib/knj/wref.rb', line 68 def destroy @map.clear @map = nil @args = nil end |
#get(id) ⇒ Object Also known as: []
Returns a object by ID or raises a RefError.
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/knj/wref.rb', line 81 def get(id) raise WeakRef::RefError if !@map.key?(id) begin return @map[id].get rescue WeakRef::RefError => e begin @map[id].destroy rescue NoMethodError #happens if the object already got destroyed by another thread - ignore. end @map.delete(id) raise e end end |
#get!(id) ⇒ Object
The same as ‘get’ but returns nil instead of WeakRef-error. This can be used to avoid writing lots of code.
108 109 110 111 112 113 114 |
# File 'lib/knj/wref.rb', line 108 def get!(id) begin return self.get(id) rescue WeakRef::RefError return nil end end |
#key?(key) ⇒ Boolean Also known as: has_key?
Make it hash-compatible.
99 100 101 |
# File 'lib/knj/wref.rb', line 99 def key?(key) return @map.key?(key) end |