Class: Ncn::Cache

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Cache

Returns a new instance of Cache.



5
6
7
# File 'lib/ncn/cache.rb', line 5

def initialize(path)
  @path = path
end

Instance Attribute Details

#pathObject (readonly)

Returns the value of attribute path.



3
4
5
# File 'lib/ncn/cache.rb', line 3

def path
  @path
end

Instance Method Details

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


14
15
16
# File 'lib/ncn/cache.rb', line 14

def exist?(key)
  cache.key?(key.to_s)
end

#fetch(key, value = nil) ⇒ Object



9
10
11
12
# File 'lib/ncn/cache.rb', line 9

def fetch(key, value = nil)
  return get(key) if exist?(key)
  (value || (block_given? ? yield : nil))&.tap { set(key, _1) }
end

#get(key) ⇒ Object



28
29
30
# File 'lib/ncn/cache.rb', line 28

def get(key)
  cache[key.to_s]
end

#keysObject



38
39
40
# File 'lib/ncn/cache.rb', line 38

def keys
  cache.keys
end

#set(key, value) ⇒ Object

Add key with associated value to the cache

Parameters:

  • cache (String)

    key

  • value (String)

    to associate with the key

Returns:

  • (Object)

    original value



22
23
24
25
26
# File 'lib/ncn/cache.rb', line 22

def set(key, value)
  cache[key.to_s] = value
  persist
  value
end

#unset(key) ⇒ Object



32
33
34
35
36
# File 'lib/ncn/cache.rb', line 32

def unset(key)
  return unless exist?(key)
  cache.delete(key.to_s)
  persist
end