Class: CloudConfig::Cache::InMemory
- Inherits:
-
Object
- Object
- CloudConfig::Cache::InMemory
- 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.
Constant Summary collapse
- DEFAULT_EXPIRE =
Default time to expire keys (seconds)
60 * 60
Instance Attribute Summary collapse
-
#settings ⇒ Object
readonly
Returns the value of attribute settings.
Instance Method Summary collapse
-
#delete(key) ⇒ Object
Delete the key from the cache.
-
#expire(key) ⇒ Object
Expire the key from the cache, if the expiry time has passed.
-
#get(key) ⇒ Object
Fetch the key from the cache.
-
#initialize ⇒ InMemory
constructor
A new instance of InMemory.
-
#key?(key) ⇒ Boolean
Check whether the key exists in the cache.
-
#set(key, value, options = {}) ⇒ Object
Set the value of the key in the cache.
Constructor Details
#initialize ⇒ InMemory
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
#settings ⇒ Object (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
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
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
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.
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.
57 58 59 60 61 62 63 64 65 66 |
# File 'lib/cloud-config/cache/in_memory.rb', line 57 def set(key, value, = {}) expire_in = [:expire_in] || DEFAULT_EXPIRE expire_at = Time.now + expire_in settings[key] = { value:, expire_at: } end |