Class: HTTPClient::LRUCache

Inherits:
Object
  • Object
show all
Defined in:
lib/httpclient/lru_cache.rb

Defined Under Namespace

Classes: Datum

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts = {}) ⇒ LRUCache

Returns a new instance of LRUCache.



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/httpclient/lru_cache.rb', line 14

def initialize(opts={})
  @max_size = Integer(opts[:max_size] || 100)
  @ttl = Float(opts[:ttl] || 0)
  @soft_ttl = Float(opts[:soft_ttl] || 0)
  @retry_delay = Float(opts[:retry_delay] || 0)
  raise "max_size must not be negative" if @max_size < 0
  raise "ttl must not be negative" if @ttl < 0
  raise "soft_ttl must not be negative" if @soft_ttl < 0
  raise "retry_delay must not be negative" if @retry_delay < 0

  @data = LruRedux::Cache.new(@max_size)
end

Instance Attribute Details

#max_sizeObject (readonly)

Returns the value of attribute max_size.



12
13
14
# File 'lib/httpclient/lru_cache.rb', line 12

def max_size
  @max_size
end

#retry_delayObject (readonly)

Returns the value of attribute retry_delay.



12
13
14
# File 'lib/httpclient/lru_cache.rb', line 12

def retry_delay
  @retry_delay
end

#soft_ttlObject (readonly)

Returns the value of attribute soft_ttl.



12
13
14
# File 'lib/httpclient/lru_cache.rb', line 12

def soft_ttl
  @soft_ttl
end

#ttlObject (readonly)

Returns the value of attribute ttl.



12
13
14
# File 'lib/httpclient/lru_cache.rb', line 12

def ttl
  @ttl
end

Instance Method Details

#fetch(key) ⇒ Object Also known as: []



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/httpclient/lru_cache.rb', line 36

def fetch(key)
  datum = @data[key]
  if datum.nil?
    store(key, value = yield)
  elsif datum.expired?
    delete(key)
    store(key, value = yield)
  elsif datum.soft_expired?
    begin
      store(key, value = yield)
    rescue RuntimeError => e
      datum.soft_expiration = (Time.now + retry_delay) if retry_delay > 0
      datum.value
    end
  else
    datum.value
  end
end

#store(key, value) ⇒ Object Also known as: []=



27
28
29
30
31
32
# File 'lib/httpclient/lru_cache.rb', line 27

def store(key, value)
  expiration = Time.now + @ttl
  soft_expiration = Time.now + @soft_ttl
  @data[key] = Datum.new(value, expiration, soft_expiration)
  value
end