Class: TimeHash

Inherits:
Object
  • Object
show all
Defined in:
lib/time-hash.rb

Constant Summary collapse

ConfusionError =
Class.new(StandardError)

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(automatic_expiration = true) ⇒ TimeHash

Returns a new instance of TimeHash.



8
9
10
11
12
# File 'lib/time-hash.rb', line 8

def initialize(automatic_expiration = true)
  @automatic_expiration = automatic_expiration
  @times = {}
  @internal = {}
end

Instance Attribute Details

#automatic_expirationObject

Returns the value of attribute automatic_expiration.



5
6
7
# File 'lib/time-hash.rb', line 5

def automatic_expiration
  @automatic_expiration
end

#timesObject (readonly)

Returns the value of attribute times.



6
7
8
# File 'lib/time-hash.rb', line 6

def times
  @times
end

Instance Method Details

#[]=(*args) ⇒ Object

Raises:



39
40
41
42
# File 'lib/time-hash.rb', line 39

def []=(*args)
  raise(ConfusionError,
        "Don't use standard key-value assignment with TimeHashes, please.")
end

#expire!Object



14
15
16
17
18
19
20
21
22
# File 'lib/time-hash.rb', line 14

def expire!
  @times.clone.each do |key, times|
    if expired?(key)
      @internal.delete(key)
      @times.delete(key)
    end
  end
  self
end

#expired?(key) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
28
# File 'lib/time-hash.rb', line 24

def expired?(key)
  return true unless @times.has_key?(key)
  time, ttl = @times[key]
  Time.now - time > ttl
end

#put(key, value, ttl) ⇒ Object

ms



30
31
32
33
34
35
# File 'lib/time-hash.rb', line 30

def put(key, value, ttl) # ms
  expire!
  response = (@internal[key] = value)
  @times[key] = [Time.now, ttl]
  response
end