Skip to content

Instantly share code, notes, and snippets.

@adamsanderson
Created January 3, 2011 01:20
Show Gist options
  • Save adamsanderson/763007 to your computer and use it in GitHub Desktop.
Save adamsanderson/763007 to your computer and use it in GitHub Desktop.
An example of using WeakRef for caching data
require 'weakref'
class TransientCache < Hash
class AmbivalentRef < WeakRef
def __getobj__
super rescue nil
end
end
def []= key, object
super(key, AmbivalentRef.new(object))
end
def [] key
ref = super(key)
self.delete(key) if !ref.weakref_alive?
ref
end
end
# Here is a silly little example:
if __FILE__ == $0
## Sample usage
c = TransientCache.new
x = "important"
c[:a] = "Hello"
c[:b] = Object.new
c[:x] = x
# Lets see what was in the cache
puts c[:a].inspect
puts c[:b].inspect
puts c[:x].inspect
# Force garbage collection.
# This will collect the weak-refs that are no longer within scope.
# This doesn't guarantee they are removed though.
puts "*** Garbage Collection ***"
ObjectSpace.garbage_collect
puts c[:a].inspect
puts c[:b].inspect
puts c[:x].inspect
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment