Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby object cache

Tags:

caching

ruby

map

I have a number of Ruby objects with unique IDs that I am currently caching in a Hash. When an object is assigned an ID, it goes into the Hash. The cache is complete, i.e. every object with an ID that exists in the Ruby scope should also be in the cache.

However, I am having trouble finding a way to delete objects from the cache once they disappear from all other scopes. This is, of course, because objects contained in the cache will not be garbage collected.

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

like image 561
Vortico Avatar asked Oct 22 '22 15:10

Vortico


1 Answers

Something similar to WeakHash will do it. 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
like image 163
Linuxios Avatar answered Oct 24 '22 11:10

Linuxios