Class: FakeRedis::ExpiringHash

Inherits:
Hash
  • Object
show all
Defined in:
lib/fakeredis/expiring_hash.rb

Overview

Represents a normal hash with some additional expiration information associated with each key

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeExpiringHash

Returns a new instance of ExpiringHash.



7
8
9
10
# File 'lib/fakeredis/expiring_hash.rb', line 7

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

Instance Attribute Details

#expiresObject (readonly)

Returns the value of attribute expires.



5
6
7
# File 'lib/fakeredis/expiring_hash.rb', line 5

def expires
  @expires
end

Instance Method Details

#[](key) ⇒ Object



12
13
14
15
16
# File 'lib/fakeredis/expiring_hash.rb', line 12

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

#[]=(key, val) ⇒ Object



18
19
20
21
22
# File 'lib/fakeredis/expiring_hash.rb', line 18

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

#delete(key) ⇒ Object



24
25
26
27
28
# File 'lib/fakeredis/expiring_hash.rb', line 24

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

#expire(key) ⇒ Object



30
31
32
33
# File 'lib/fakeredis/expiring_hash.rb', line 30

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

#expired?(key) ⇒ Boolean

Returns:

  • (Boolean)


35
36
37
38
# File 'lib/fakeredis/expiring_hash.rb', line 35

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

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


40
41
42
43
44
# File 'lib/fakeredis/expiring_hash.rb', line 40

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

#keysObject



52
53
54
55
56
57
58
59
60
61
62
# File 'lib/fakeredis/expiring_hash.rb', line 52

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

#normalize(key) ⇒ Object



64
65
66
# File 'lib/fakeredis/expiring_hash.rb', line 64

def normalize key
  key.to_s
end

#values_at(*keys) ⇒ Object



46
47
48
49
50
# File 'lib/fakeredis/expiring_hash.rb', line 46

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