Class: MemoriClient::ClientFactory

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/memori_client/client_factory.rb

Overview

ClientFactory is a singleton class responsible for creating and caching MemoriClient::Client instances for different namespaces and kinds.

This factory pattern ensures that only one client instance exists per namespace/kind combination, improving performance and resource usage.

Examples:

Basic usage

factory = MemoriClient::ClientFactory.instance
client = factory.get_client(
  namespace: 'my_app',
  kind: MemoriClient::ClientFactory::Kinds::BACKEND,
  uri: 'https://api.example.com',
  api_root: '/api/v1'
)

Since:

  • 1.0.0

Defined Under Namespace

Modules: Kinds

Instance Method Summary collapse

Constructor Details

#initializeClientFactory

Initializes a new ClientFactory instance. Sets up empty hashes to cache backend and engine clients by namespace.

Since:

  • 1.0.0



35
36
37
38
# File 'lib/memori_client/client_factory.rb', line 35

def initialize
  @backend_clients = {}
  @engine_clients = {}
end

Instance Method Details

#get_client(namespace:, kind:, uri:, api_root:) ⇒ MemoriClient::Client

Gets or creates a cached client instance for the specified parameters.

This method implements a lazy initialization pattern where clients are only created when first requested and then cached for subsequent use.

Examples:

Get a backend client

client = factory.get_client(
  namespace: 'production',
  kind: Kinds::BACKEND,
  uri: 'https://api.memori.ai',
  api_root: '/api/v1'
)

Get an engine client

client = factory.get_client(
  namespace: 'staging',
  kind: Kinds::ENGINE,
  uri: 'https://engine.memori.ai',
  api_root: '/engine/v1'
)

Raises:

  • (RuntimeError)

    If an invalid kind is provided.

Since:

  • 1.0.0



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/memori_client/client_factory.rb', line 71

def get_client(namespace:, kind:, uri:, api_root:)
  # Validate that the provided kind is supported
  raise "Invalid kind: #{kind}" unless known_kinds.include?(kind)

  case kind
  when Kinds::BACKEND
    # Use memoization to return cached client or create new one
    @backend_clients[namespace] ||= MemoriClient::Client.new(namespace: namespace, 
      kind: kind, 
      uri: uri, 
      api_root: api_root)
  when Kinds::ENGINE
    # Use memoization to return cached client or create new one
    @engine_clients[namespace] ||= MemoriClient::Client.new(namespace: namespace, 
      kind: kind, 
      uri: uri, 
      api_root: api_root)
  end
end