Class: AwsDevUtils::Cache

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Singleton
Defined in:
lib/aws-dev-utils/cache.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#backend=(value) ⇒ Object

Injectable backend.



9
10
11
# File 'lib/aws-dev-utils/cache.rb', line 9

def backend=(value)
  @backend = value
end

Instance Method Details

#fetch(key, exp = 60, &block) ⇒ Object

Returns a value from the cache for the given key. If the key can’t be found, the block will be run and its result returned and be set in the cache.

Parameters:

  • key (Object)
  • exp (Integer) (defaults to: 60)
  • block (block)
    • called with no arguments, and returns the new value for the cache (if no cached data is found).

Returns:

  • (Object)

    the value from the cache or the result of the block



22
23
24
# File 'lib/aws-dev-utils/cache.rb', line 22

def fetch key, exp=60, &block
  get(key) or block.().tap {|x| set(key, x, exp)}
end

#get(key) ⇒ Object

Get the value of key. If not found, returns nil



27
28
29
# File 'lib/aws-dev-utils/cache.rb', line 27

def get key
  deserialize backend.get key.to_s rescue nil
end

#set(key, value, expiration) ⇒ Object

Set key to hold the value and set key to timeout after the a given expiration time(in seconds).

Parameters:

  • key (Object)
  • value (Object)
  • expiration (Time, Integer)
    • the key-value timeout



35
36
37
# File 'lib/aws-dev-utils/cache.rb', line 35

def set key, value, expiration
  backend.set key.to_s, serialize(value), expiration rescue nil
end