Sha256: 3c079a69f88c1fa0af24a1ccc1da44c51739503db83ebd1db8bde5ccddcddfea

Contents?: true

Size: 933 Bytes

Versions: 34

Compression:

Stored size: 933 Bytes

Contents

require 'monitor'

module Looksist
  class SafeLruCache < Hash

    include MonitorMixin

    def initialize(max_size)
      @max_size = max_size
      super(nil)
    end

    def []=(key, val)
      synchronize do
        super(key, val)
        pop
        val
      end
    end

    def merge!(hash)
      synchronize do
        super(hash)
        (count - @max_size).times { pop }
      end
    end

    def mslice(keys)
      synchronize do
        keys.collect { |k| self[k] }
      end
    end

    private

    def pop
      # not using shift coz: http://bugs.ruby-lang.org/issues/8312
      delete(first[0]) if count > @max_size
    end

    def self.synchronize(*methods)
      methods.each do |method|
        define_method method do |*args, &blk|
          synchronize do
            super(*args, &blk)
          end
        end
      end
    end

    synchronize :[], :each, :to_a, :delete, :count, :has_key?

  end
end

Version data entries

34 entries across 34 versions & 1 rubygems

Version Path
looksist-0.2.3 lib/looksist/safe_lru_cache.rb
looksist-0.2.2 lib/looksist/safe_lru_cache.rb
looksist-0.2.1 lib/looksist/safe_lru_cache.rb
looksist-0.2.0 lib/looksist/safe_lru_cache.rb
looksist-0.1.9 lib/looksist/safe_lru_cache.rb
looksist-0.1.8 lib/looksist/safe_lru_cache.rb
looksist-0.1.7 lib/looksist/safe_lru_cache.rb
looksist-0.1.6 lib/looksist/safe_lru_cache.rb
looksist-0.1.5 lib/looksist/safe_lru_cache.rb
looksist-0.1.4 lib/looksist/safe_lru_cache.rb
looksist-0.1.3 lib/looksist/safe_lru_cache.rb
looksist-0.1.2 lib/looksist/safe_lru_cache.rb
looksist-0.1.1 lib/looksist/safe_lru_cache.rb
looksist-0.1.0 lib/looksist/safe_lru_cache.rb