Class: CacheMock

Inherits:
Object
  • Object
show all
Defined in:
lib/cache_mock.rb,
lib/cache_mock/version.rb

Constant Summary collapse

VERSION =
"0.1.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCacheMock

Returns a new instance of CacheMock.



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

def initialize()
  @db = {}
end

Instance Attribute Details

#dbObject (readonly)

Returns the value of attribute db.



4
5
6
# File 'lib/cache_mock.rb', line 4

def db
  @db
end

Instance Method Details

#clearObject



26
27
28
# File 'lib/cache_mock.rb', line 26

def clear
  @db = {}
end

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/cache_mock.rb', line 30

def exist?(key)
  db.key?(key) && (db[key][:expiration_time] > Time.now.to_i)
end

#fetch(key, options = {}, &block) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/cache_mock.rb', line 9

def fetch(key, options = {}, &block)

  if exist?(key)
    # fetch and return result
    db[key][:value]
  else
    if block_given?
      # make the DB query and create a new entry for the request result
      db[key] = build_record(options, &block)
      db[key][:value]
    else
      # no block given, do nothing
      nil
    end
  end
end

#read(key) ⇒ Object



34
35
36
# File 'lib/cache_mock.rb', line 34

def read(key)
  db[key][:value] if exist?(key)
end

#write(key, value, options = {}) ⇒ Object



38
39
40
41
# File 'lib/cache_mock.rb', line 38

def write(key, value, options = {})
  db[key] = build_record(options) { value }
  value
end