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.3.12 lib/looksist/safe_lru_cache.rb
looksist-0.3.11 lib/looksist/safe_lru_cache.rb
looksist-0.3.10 lib/looksist/safe_lru_cache.rb
looksist-0.3.9 lib/looksist/safe_lru_cache.rb
looksist-0.3.8 lib/looksist/safe_lru_cache.rb
looksist-0.3.7 lib/looksist/safe_lru_cache.rb
looksist-0.3.6 lib/looksist/safe_lru_cache.rb
looksist-0.3.5 lib/looksist/safe_lru_cache.rb
looksist-0.3.4 lib/looksist/safe_lru_cache.rb
looksist-0.3.3 lib/looksist/safe_lru_cache.rb
looksist-0.3.2 lib/looksist/safe_lru_cache.rb
looksist-0.3.1 lib/looksist/safe_lru_cache.rb
looksist-0.3.0 lib/looksist/safe_lru_cache.rb
looksist-0.2.10 lib/looksist/safe_lru_cache.rb
looksist-0.2.9 lib/looksist/safe_lru_cache.rb
looksist-0.2.8 lib/looksist/safe_lru_cache.rb
looksist-0.2.7 lib/looksist/safe_lru_cache.rb
looksist-0.2.6 lib/looksist/safe_lru_cache.rb
looksist-0.2.5 lib/looksist/safe_lru_cache.rb
looksist-0.2.4 lib/looksist/safe_lru_cache.rb