Class: Togul::Cache
- Inherits:
-
Object
- Object
- Togul::Cache
- Defined in:
- lib/togul/cache.rb
Instance Method Summary collapse
- #flush ⇒ Object
-
#get(key) ⇒ Boolean?
Cached value or nil on miss/expiry.
-
#initialize(ttl:) ⇒ Cache
constructor
A new instance of Cache.
- #invalidate_flag(flag_key) ⇒ Object
- #set(key, value) ⇒ Object
Constructor Details
#initialize(ttl:) ⇒ Cache
Returns a new instance of Cache.
5 6 7 8 9 |
# File 'lib/togul/cache.rb', line 5 def initialize(ttl:) @ttl = ttl @store = {} @mutex = Mutex.new end |
Instance Method Details
#flush ⇒ Object
31 32 33 |
# File 'lib/togul/cache.rb', line 31 def flush @mutex.synchronize { @store.clear } end |
#get(key) ⇒ Boolean?
Returns cached value or nil on miss/expiry.
12 13 14 15 16 17 18 19 20 |
# File 'lib/togul/cache.rb', line 12 def get(key) @mutex.synchronize do entry = @store[key] return nil unless entry return nil if Time.now.to_f > entry[:expires_at] entry[:value] end end |
#invalidate_flag(flag_key) ⇒ Object
35 36 37 38 39 40 |
# File 'lib/togul/cache.rb', line 35 def invalidate_flag(flag_key) prefix = "#{flag_key}:" @mutex.synchronize do @store.delete_if { |key, _| key.start_with?(prefix) } end end |
#set(key, value) ⇒ Object
22 23 24 25 26 27 28 29 |
# File 'lib/togul/cache.rb', line 22 def set(key, value) @mutex.synchronize do @store[key] = { value: value, expires_at: Time.now.to_f + @ttl } end end |