Class: Hitnmiss::InMemoryDriver

Inherits:
Object
  • Object
show all
Includes:
Driver::Interface
Defined in:
lib/hitnmiss/in_memory_driver.rb

Instance Method Summary collapse

Constructor Details

#initializeInMemoryDriver

Returns a new instance of InMemoryDriver.



5
6
7
8
# File 'lib/hitnmiss/in_memory_driver.rb', line 5

def initialize
  @mutex = Mutex.new
  @cache = {}
end

Instance Method Details

#all(keyspace) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/hitnmiss/in_memory_driver.rb', line 47

def all(keyspace)
  @mutex.synchronize do
    matching_values = []
    @cache.each do |key, entity|
      matching_values << entity.fetch('value') if match_keyspace?(key, keyspace)
    end
    return matching_values
  end
end

#clear(keyspace) ⇒ Object



63
64
65
66
67
# File 'lib/hitnmiss/in_memory_driver.rb', line 63

def clear(keyspace)
  @mutex.synchronize do
    @cache.delete_if { |key, _| match_keyspace?(key, keyspace) }
  end
end

#delete(key) ⇒ Object



57
58
59
60
61
# File 'lib/hitnmiss/in_memory_driver.rb', line 57

def delete(key)
  @mutex.synchronize do
    @cache.delete(key)
  end
end

#get(key) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/hitnmiss/in_memory_driver.rb', line 29

def get(key)
  cached_entity = nil
  @mutex.synchronize do
    cached_entity = @cache[key].dup if @cache[key]
  end

  return Hitnmiss::Driver::Miss.new if cached_entity.nil?

  if cached_entity.has_key?('expiration')
    if Time.now.to_i >= cached_entity['expiration']
      return Hitnmiss::Driver::Miss.new
    end
  end

  return Hitnmiss::Driver::Hit.new(cached_entity['value'],
                                   build_hit_keyword_args(cached_entity))
end

#match_keyspace?(key, keyspace) ⇒ Boolean

Returns:

  • (Boolean)


69
70
71
72
# File 'lib/hitnmiss/in_memory_driver.rb', line 69

def match_keyspace?(key, keyspace)
  regex = Regexp.new("^#{keyspace}\\" + Repository::KeyGeneration::KEY_COMPONENT_SEPARATOR)
  return regex.match(key)
end

#set(key, entity) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/hitnmiss/in_memory_driver.rb', line 10

def set(key, entity)
  if entity.expiration
    expiration = Time.now.to_i + entity.expiration
    @mutex.synchronize do
      @cache[key] = { 'value' => entity.value, 'expiration' => expiration }
      @cache[key]['fingerprint'] = entity.fingerprint if entity.fingerprint
      @cache[key]['updated_at'] = internal_timestamp
      @cache[key]['last_modified'] = entity.last_modified if entity.last_modified
    end
  else
    @mutex.synchronize do
      @cache[key] = { 'value' => entity.value }
      @cache[key]['fingerprint'] = entity.fingerprint if entity.fingerprint
      @cache[key]['updated_at'] = internal_timestamp
      @cache[key]['last_modified'] = entity.last_modified if entity.last_modified
    end
  end
end