Class: Ollama::Documents::RedisCache

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of RedisCache.



4
5
6
7
# File 'lib/ollama/documents/redis_cache.rb', line 4

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

Instance Attribute Details

#prefix=(value) ⇒ Object (writeonly)

Sets the attribute prefix

Parameters:

  • value

    the value to set the attribute prefix to.



9
10
11
# File 'lib/ollama/documents/redis_cache.rb', line 9

def prefix=(value)
  @prefix = value
end

Instance Method Details

#[](key) ⇒ Object



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

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

#[]=(key, value) ⇒ Object



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

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

#clearObject



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

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

#delete(key) ⇒ Object



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

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

#each(&block) ⇒ Object



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

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

#key?(key) ⇒ Boolean

Returns:

  • (Boolean)


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

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

#pre(key) ⇒ Object



51
52
53
# File 'lib/ollama/documents/redis_cache.rb', line 51

def pre(key)
  [ @prefix, key ].join
end

#redisObject



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

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

#sizeObject



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

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

#unpre(key) ⇒ Object



55
56
57
# File 'lib/ollama/documents/redis_cache.rb', line 55

def unpre(key)
  key.sub(/\A#@prefix/, '')
end