Class: Istox::RemoteModelCache

Inherits:
Object
  • Object
show all
Defined in:
lib/istox/helpers/remote_model_cache.rb

Class Method Summary collapse

Class Method Details

.cache(data:, key:, fields: nil, field: nil) ⇒ Object

keys must be an array



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/istox/helpers/remote_model_cache.rb', line 8

def cache(data:, key:, fields: nil, field: nil)
  fields = [] if fields.blank?
  fields.push(field) if field.present?

  key = key.to_s

  raise 'Fields cannot be empty' if fields.empty?

  log.debug "Writing data to cache, key: #{key}, fields: #{fields.inspect}"
  log.debug "Cache data: #{data.inspect}"

  data = data.to_json unless data.instance_of?(String)

  Thread.new do
    results = fields.map do |f|
      redis.hset(key, f.to_s, data)
    end

    log.debug "Cache results: #{results.inspect}"
  rescue StandardError => e
    log.error 'Failed to cache data'
    log.error e
  end
end

.flushObject



76
77
78
# File 'lib/istox/helpers/remote_model_cache.rb', line 76

def flush
  redis.flushdb
end

.get(key:, field:, auto_convert_openstruct: true) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/istox/helpers/remote_model_cache.rb', line 52

def get(key:, field:, auto_convert_openstruct: true)
  raise 'You must provide a callback block if cache doesnt exist' unless block_given?

  key = key.to_s
  field = field.to_s

  result = redis.hget(key, field)

  log.debug "Getting data from cache, key: #{key}, field: #{field}, result: #{result.inspect}"

  if result.present?
    begin
      return auto_convert_openstruct ? ::Istox::CommonHelper.to_open_struct(JSON.parse(result)) : result
    rescue StandardError => e
      log.warn('Unable to process result from cache store, is it not a json?')
      log.warn(e)
    end
  else
    log.debug 'Fallback to data retrieval block.'
  end

  yield if block_given?
end

.redisObject



80
81
82
# File 'lib/istox/helpers/remote_model_cache.rb', line 80

def redis
  ::Istox::RedisManager.remote_model_redis
end

.remove(key:, fields: nil, field: nil) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/istox/helpers/remote_model_cache.rb', line 33

def remove(key:, fields: nil, field: nil)
  fields = [] if fields.blank?
  fields.push(field) if field.present?

  key = key.to_s

  raise 'Fields cannot be empty' if fields.empty?

  fields = fields.map(&:to_s)

  fields.each do |f|
    next unless redis.hexists(key, f)

    log.debug "Deleting cache data for key: #{key}, field: #{f}"

    redis.hdel(key, [f])
  end
end