Class: OllamaChat::Utils::CacheFetcher

Inherits:
Object
  • Object
show all
Defined in:
lib/ollama_chat/utils/cache_fetcher.rb

Instance Method Summary collapse

Constructor Details

#initialize(cache) ⇒ void

The initialize method sets up the cache instance variable for the object.

Parameters:

  • cache (Object)

    the cache object to be stored



9
10
11
# File 'lib/ollama_chat/utils/cache_fetcher.rb', line 9

def initialize(cache)
  @cache = cache
end

Instance Method Details

#get(url) {|io| ... } ⇒ Object

The get method retrieves cached content by key and yields it as an IO object. It first checks if the body and content type are present in the cache. If both are found, it creates a StringIO object from the body, extends it with HeaderExtension, sets the content type, and then yields the IO object to the provided block.

Parameters:

  • url (String)

    the URL used as a key for caching

Yields:

  • (io)

    yields the cached IO object if found



22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/ollama_chat/utils/cache_fetcher.rb', line 22

def get(url, &block)
  block or raise ArgumentError, 'require block argument'
  body         = @cache[key(:body, url)]
  content_type = @cache[key(:content_type, url)]
  content_type = MIME::Types[content_type].first
  if body && content_type
    io = StringIO.new(body)
    io.rewind
    io.extend(OllamaChat::Utils::Fetcher::HeaderExtension)
    io.content_type = content_type
    block.(io)
  end
end

#put(url, io) ⇒ CacheFetcher

The put method stores the body and content type of an IO object in the cache using a URL-based key.

Parameters:

  • url (String)

    the URL used to generate the cache key

  • io (StringIO, Tempfile)

    the IO object containing the body and content type

Returns:

  • (CacheFetcher)

    returns itself to allow for method chaining



43
44
45
46
47
48
49
50
51
52
# File 'lib/ollama_chat/utils/cache_fetcher.rb', line 43

def put(url, io)
  io.rewind
  body = io.read
  body.empty? and return
  content_type = io.content_type
  content_type.nil? and return
  @cache.set(key(:body, url), body, ex: io.ex)
  @cache.set(key(:content_type,  url), content_type.to_s, ex: io.ex)
  self
end