Class: Ollama::Documents::RedisCache

Inherits:
Object
  • Object
show all
Includes:
Enumerable, Cache::Common
Defined in:
lib/ollama/documents/cache/redis_cache.rb

Instance Attribute Summary

Attributes included from Cache::Common

#prefix

Instance Method Summary collapse

Methods included from Cache::Common

#collections, #pre, #unpre

Constructor Details

#initialize(prefix:, url: ENV['REDIS_URL']) ⇒ RedisCache

Returns a new instance of RedisCache.



7
8
9
10
# File 'lib/ollama/documents/cache/redis_cache.rb', line 7

def initialize(prefix:, url: ENV['REDIS_URL'])
  url or raise ArgumentError, 'require redis url'
  @prefix, @url = prefix, url
end

Instance Method Details

#[](key) ⇒ Object



16
17
18
19
20
21
# File 'lib/ollama/documents/cache/redis_cache.rb', line 16

def [](key)
  value = redis.get(pre(key))
  unless value.nil?
    JSON(value, object_class: Ollama::Documents::Record)
  end
end

#[]=(key, value) ⇒ Object



23
24
25
# File 'lib/ollama/documents/cache/redis_cache.rb', line 23

def []=(key, value)
  redis.set(pre(key), JSON(value))
end

#clearObject



41
42
43
44
# File 'lib/ollama/documents/cache/redis_cache.rb', line 41

def clear
  redis.scan_each(match: "#@prefix*") { |key| redis.del(key) }
  self
end

#delete(key) ⇒ Object



31
32
33
# File 'lib/ollama/documents/cache/redis_cache.rb', line 31

def delete(key)
  redis.del(pre(key)) == 1
end

#each(&block) ⇒ Object



46
47
48
49
# File 'lib/ollama/documents/cache/redis_cache.rb', line 46

def each(&block)
  redis.scan_each(match: "#@prefix*") { |key| block.(key, self[unpre(key)]) }
  self
end

#full_each(&block) ⇒ Object



52
53
54
55
56
57
58
# File 'lib/ollama/documents/cache/redis_cache.rb', line 52

def full_each(&block)
  redis.scan_each do |key|
    value = redis.get(key) or next
    value = JSON(value, object_class: Ollama::Documents::Record)
    block.(key, value)
  end
end

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
# File 'lib/ollama/documents/cache/redis_cache.rb', line 27

def key?(key)
  !!redis.exists?(pre(key))
end

#redisObject



12
13
14
# File 'lib/ollama/documents/cache/redis_cache.rb', line 12

def redis
  @redis ||= Redis.new(url: @url)
end

#sizeObject



35
36
37
38
39
# File 'lib/ollama/documents/cache/redis_cache.rb', line 35

def size
  s = 0
  redis.scan_each(match: "#@prefix*") { |key| s += 1 }
  s
end