Class: OllamaChat::Utils::CacheFetcher

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

Overview

A cache fetcher implementation that handles caching of HTTP responses with content type metadata.

This class provides a mechanism to store and retrieve cached HTTP responses, including their content types, using a key-based system. It is designed to work with various cache backends and ensures that both the response body and metadata are properly cached and retrieved for efficient subsequent requests.

Examples:

Using the CacheFetcher to cache and retrieve HTTP responses

cache = Redis.new
fetcher = OllamaChat::Utils::CacheFetcher.new(cache)
fetcher.put('https://example.com', io)
fetcher.get('https://example.com') do |cached_io|
  # Process cached content
end

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



24
25
26
# File 'lib/ollama_chat/utils/cache_fetcher.rb', line 24

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



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/ollama_chat/utils/cache_fetcher.rb', line 37

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



58
59
60
61
62
63
64
65
66
67
# File 'lib/ollama_chat/utils/cache_fetcher.rb', line 58

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