Sha256: 9fea6c40eed5d1822bc4d31bf2da6c4ecaf7244c265b7766e0af4b7c20ddbd14

Contents?: true

Size: 1.17 KB

Versions: 4

Compression:

Stored size: 1.17 KB

Contents

module FakeRedis
  # Represents a normal hash with some additional expiration information
  # associated with each key
  class ExpiringHash < Hash
    attr_reader :expires

    def initialize(*)
      super
      @expires = {}
    end

    def [](key)
      key = normalize key
      delete(key) if expired?(key)
      super
    end

    def []=(key, val)
      key = normalize key
      expire(key)
      super
    end

    def delete(key)
      key = normalize key
      expire(key)
      super
    end

    def expire(key)
      key = normalize key
      expires.delete(key)
    end

    def expired?(key)
      key = normalize key
      expires.include?(key) && expires[key] <= Time.now
    end

    def key?(key)
      key = normalize key
      delete(key) if expired?(key)
      super
    end

    def values_at(*keys)
      keys.each do |key|
        key = normalize(key)
        delete(key) if expired?(key)
      end
      super
    end

    def keys
      super.select do |key|
        key = normalize(key)
        if expired?(key)
          delete(key)
          false
        else
          true
        end
      end
    end

    def normalize key
      key.to_s
    end
  end
end

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
fakeredis-0.7.0 lib/fakeredis/expiring_hash.rb
kuende-fakeredis-0.10.0 lib/fakeredis/expiring_hash.rb
fakeredis-0.6.0 lib/fakeredis/expiring_hash.rb
kuende-fakeredis-0.6.0 lib/fakeredis/expiring_hash.rb