Class: CloudConfig::Cache::InMemory

Inherits:
Object
  • Object
show all
Defined in:
lib/cloud-config/cache/in_memory.rb

Overview

A simple class for storing key-value configuration in-memory. Keys can be individuallly set to expire.

Examples:

cache = CloudConfig::Cache::InMemory.new
cache.set(:key_to_expire, :key_value, expire_in: 5)

cache.get(:key_to_expire) #=> :key_value

sleep 5

cache.get(:key_to_expire) #=> nil

Constant Summary collapse

DEFAULT_EXPIRE =

Default time to expire keys (seconds)

60 * 60

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeInMemory

Returns a new instance of InMemory.



25
26
27
# File 'lib/cloud-config/cache/in_memory.rb', line 25

def initialize
  @settings = {}
end

Instance Attribute Details

#settingsObject (readonly)

Returns the value of attribute settings.



23
24
25
# File 'lib/cloud-config/cache/in_memory.rb', line 23

def settings
  @settings
end

Instance Method Details

#delete(key) ⇒ Object

Delete the key from the cache

Parameters:

  • key (String, Symbol)

    Key to delete



71
72
73
# File 'lib/cloud-config/cache/in_memory.rb', line 71

def delete(key)
  settings.delete(key)
end

#expire(key) ⇒ Object

Expire the key from the cache, if the expiry time has passed

Parameters:

  • key (String, Symbol)

    Key to expire



78
79
80
81
82
# File 'lib/cloud-config/cache/in_memory.rb', line 78

def expire(key)
  expire_at = settings.dig(key, :expire_at)

  delete(key) if expire_at && expire_at <= Time.now
end

#get(key) ⇒ Object

Fetch the key from the cache

Parameters:

  • key (String, Symbol)

    Key to check

Returns:

  • (Object)

    Value of key



45
46
47
48
49
# File 'lib/cloud-config/cache/in_memory.rb', line 45

def get(key)
  expire(key)

  settings.dig(key, :value)
end

#key?(key) ⇒ Boolean

Check whether the key exists in the cache. Expired keys will return false.

Parameters:

  • key (String, Symbol)

    Key to check

Returns:

  • (Boolean)

    Whether key exists



34
35
36
37
38
# File 'lib/cloud-config/cache/in_memory.rb', line 34

def key?(key)
  expire(key)

  settings.key?(key)
end

#set(key, value, options = {}) ⇒ Object

Set the value of the key in the cache. Optionally set an expiry of the key, otherwise a default expiry of DEFAULT_EXPIRE will be set.

Parameters:

  • key (String, Symbol)

    Key to set

  • value (Object)

    Value of the key

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :expire_in (Hash)

    Time in seconds until key expires



57
58
59
60
61
62
63
64
65
66
# File 'lib/cloud-config/cache/in_memory.rb', line 57

def set(key, value, options = {})
  expire_in = options[:expire_in] || DEFAULT_EXPIRE

  expire_at = Time.now + expire_in

  settings[key] = {
    value:,
    expire_at:
  }
end