Ruby Cache

I have several Ruby objects with unique identifiers that I now cache in Hash. When an identifier is assigned to an object, it goes into a hash. The cache is complete, i.e. Each object with an identifier that exists in the Ruby area must also be in the cache.

However, I had problems finding a way to remove objects from the cache after they disappeared from all other areas. This, of course, is because the objects contained in the cache will not collect garbage.

Are there any approaches to this problem? The documentation for the WeakRefproposed class WeakHash, but it does not seem acceptable for practical use, although it is very close to what I think I need for my project.

+5
source share
1 answer

Something like WeakHash will do. Here's a more complete implementation that can handle Fixnums, Symbols, and Floats (and other immutable types if you add them to the list):

class WeakHash < Hash
  def []=(k, v)
    if(![Fixnum, Symbol, Float].include? k.class)
      k = WeakRef.new(k)
    end
    if(![Fixnum, Symbol, Float].include? v.class)
      v = WeakRef.new(v)
    end
    super k,v
  end
end
+3
source

All Articles