Module: Bogo::Memoization
- Defined in:
- lib/bogo/memoization.rb
Overview
Memoization helpers
Class Method Summary collapse
-
.cleanup(object_id) ⇒ Proc
Clean up isolated memoizations.
-
.clear_current! ⇒ nil
Clear thread memoizations.
-
.clear_global! ⇒ nil
Clear global memoizations.
Instance Method Summary collapse
-
#_memo ⇒ Smash
Memoization hash for current thread.
-
#clear_memoizations! ⇒ TrueClass
Remove all memoized values.
-
#memoize(key, direct = false) { ... } ⇒ Object
Memoize data.
-
#unmemoize(key, direct = false) ⇒ NilClass
Remove memoized value.
Class Method Details
.cleanup(object_id) ⇒ Proc
Clean up isolated memoizations
13 14 15 16 17 18 19 |
# File 'lib/bogo/memoization.rb', line 13 def cleanup(object_id) proc do Thread.current[:bogo_memoization].delete_if do |k,v| k.to_s.start_with?(object_id.to_s) end end end |
.clear_current! ⇒ nil
Clear thread memoizations
24 25 26 |
# File 'lib/bogo/memoization.rb', line 24 def clear_current! Thread.current[:bogo_memoization] = nil end |
Instance Method Details
#_memo ⇒ Smash
Returns memoization hash for current thread.
67 68 69 70 71 72 73 |
# File 'lib/bogo/memoization.rb', line 67 def _memo unless(Thread.current[:bogo_memoization]) Thread.current[:bogo_memoization] = Smash.new ObjectSpace.define_finalizer(self, Bogo::Memoization.cleanup(self.object_id)) end Thread.current[:bogo_memoization] end |
#clear_memoizations! ⇒ TrueClass
Remove all memoized values
97 98 99 100 101 102 103 104 |
# File 'lib/bogo/memoization.rb', line 97 def clear_memoizations! _memo.keys.find_all do |key| key.to_s.start_with?("#{self.object_id}_") end.each do |key| _memo.delete(key) end true end |
#memoize(key, direct = false) { ... } ⇒ Object
Memoize data
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/bogo/memoization.rb', line 46 def memoize(key, direct=false) unless(direct) key = "#{self.object_id}_#{key}" end if(direct == :global) Thread.exclusive do $bogo_memoization ||= Smash.new unless($bogo_memoization.has_key?(key)) $bogo_memoization[key] = yield end $bogo_memoization[key] end else unless(_memo.has_key?(key)) _memo[key] = yield end _memo[key] end end |
#unmemoize(key, direct = false) ⇒ NilClass
Remove memoized value
80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/bogo/memoization.rb', line 80 def unmemoize(key, direct=false) unless(direct) key = "#{self.object_id}_#{key}" end if(direct == :global) Thread.exclusive do $bogo_memoization ||= Smash.new $bogo_memoization.delete(key) end else _memo.delete(key) end end |