Class: LocalCacheStore

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

Overview

Implements a local in-memory cache store.

Instance Method Summary collapse

Constructor Details

#initialize(_namespace = nil) ⇒ LocalCacheStore

Returns a new instance of LocalCacheStore.



43
44
45
# File 'lib/cache_store.rb', line 43

def initialize(_namespace = nil)
  @store = {}
end

Instance Method Details

#exist?(key) ⇒ Boolean

Checks if a value exists within this cache store for a specific key.

Parameters:

  • key (String)

    The unique key to reference the value to check for within this cache store.

Returns:

  • (Boolean)

    True or False to specify if the key exists in the cache store.



97
98
99
# File 'lib/cache_store.rb', line 97

def exist?(key)
  @store.key? key
end

#get(key, expires_in = 0, &block) ⇒ Object

Gets a value from this cache store by its unique key.

Parameters:

  • key (String)

    Unique key to reference the value to fetch from within this cache store.

  • &block (Block)

    This block is provided to populate this cache store with the value for the request key when it is not found.

Returns:

  • (Object)

    The value for the specified unique key within the cache store.



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/cache_store.rb', line 64

def get(key, expires_in = 0, &block)
  item = @store[key]
  if item
    if item[:expires] && item[:expires] < Time.now # An expired entry has been found
      if block_given?
        value = yield
        set(key, value, expires_in)
        return value
      else
        remove(key)
        return nil
      end
    else # An item was found which has not expired
      return item[:value]
    end
  elsif block_given?
    value = yield
    set(key, value, expires_in)
    return value
  end
end

#remove(key) ⇒ Object

Removes a value from this cache store by its unique key.

Parameters:

  • key (String)

    The unique key to remove from this cache store.



89
90
91
# File 'lib/cache_store.rb', line 89

def remove(key)
  @store.delete key
end

#set(key, value, expires_in = 0) ⇒ Object

Stores a value in this cache store by its key.

Parameters:

  • key (String)

    The unique key to reference the value being set.

  • value (Object)

    The value to store.

  • expires_in (Integer) (defaults to: 0)

    The number of seconds from the current time that this value should expire.



52
53
54
55
56
57
# File 'lib/cache_store.rb', line 52

def set(key, value, expires_in = 0)
  if expires_in > 0
    expires = Time.now + expires_in
  end
  @store.store(key, {value: value, expires: expires})
end