Class: ZkCache

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

Class Method Summary collapse

Class Method Details

.clientObject



8
9
10
# File 'lib/caches/zk_cache.rb', line 8

def client
  @@client
end

.decode_data(data) ⇒ Object



62
63
64
65
66
# File 'lib/caches/zk_cache.rb', line 62

def decode_data(data)
  ActiveSupport::JSON.decode(data)
rescue => error
  data
end

.delete(key, options = {}) ⇒ Object



55
56
57
58
59
60
# File 'lib/caches/zk_cache.rb', line 55

def delete(key, options = {})
  key = process_key(key)
  deleted = read(key)
  client.delete(path: key)
  deleted
end

.expires?(data) ⇒ Boolean



68
69
70
71
72
# File 'lib/caches/zk_cache.rb', line 68

def expires?(data)
  return true if (data.nil? || !data.is_a?(Hash))
  data = data.with_indifferent_access
  return DateTime.parse(data[:last_read]).to_i + data[:expires_in].to_i < Time.now.to_i
end

.initializeObject



12
13
14
15
16
17
18
# File 'lib/caches/zk_cache.rb', line 12

def initialize
  config = ConfigService.load_config('zookeeper.yml')[ConfigService.environment]
  @@client ||= Zookeeper.new(config['host'])
rescue => error
  SdkLogger.logger.error("ZkCache.initialize error: #{error.message}")
  @@client ||= Zookeeper.new('localhost:2181')
end

.read(key, options = {}) ⇒ Object

Cache API, mimics ActiveSupport::Cache::Store api.rubyonrails.org/classes/ActiveSupport/Cache/Store.html



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/caches/zk_cache.rb', line 23

def read(key, options = {})
  key = process_key(key)
  result = client.get(path: key)[:data]
  result = decode_data(result)

  return result unless result.is_a?(Hash)
  
  sym_data = result.with_indifferent_access
  return sym_data unless sym_data[:zk_cache_data].present?
  
  sym_data = sym_data[:zk_cache_data]
  return nil if expires?(sym_data)

  sym_data[:value]
end

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



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/caches/zk_cache.rb', line 39

def write(key, value, options = {})
  key = process_key(key)
  init_key(key, nil)
  written_value = value
  if options[:expires_in].to_i > 0
    written_value = { zk_cache_data: { 
                                        value: value, 
                                        expires_in: (options[:expires_in].to_i),
                                        last_read: Time.now
                                      } 
                    }.to_json
  end

  client.set(path: key, data: written_value)
end