module Mongoid::Clients

Mixin module included into Mongoid::Document which adds database client connection functionality. Also contains singleton class methods related to managing database clients.

Constants

CREATE_LOCK

Public Class Methods

clear() click to toggle source

Clear all clients from the current thread.

@example Clear all clients.

Mongoid::Clients.clear

@return [ Array ] The empty clients.

# File lib/mongoid/clients.rb, line 29
def clear
  clients.clear
end
clients() click to toggle source

Returns the stored clients indexed by name.

@return [ Hash<Symbol, Mongo::Client> ] The index of clients.

# File lib/mongoid/clients.rb, line 102
def clients
  @clients ||= {}
end
default() click to toggle source

Get the default client.

@example Get the default client.

Mongoid::Clients.default

@return [ Mongo::Client ] The default client.

# File lib/mongoid/clients.rb, line 39
def default
  with_name(:default)
end
disconnect() click to toggle source

Disconnect all active clients.

@example Disconnect all active clients.

Mongoid::Clients.disconnect

@return [ true ] True.

# File lib/mongoid/clients.rb, line 49
def disconnect
  clients.each_value(&:close)
  true
end
reconnect() click to toggle source

Reconnect all active clients.

@example Reconnect all active clients.

Mongoid::Clients.reconnect

@return [ true ] True.

# File lib/mongoid/clients.rb, line 60
def reconnect
  clients.each_value(&:reconnect)
  true
end
set(name, client) click to toggle source

Store a client with the provided name.

@example Set a client.

Mongoid::Clients.set(:analytics, my_client)

@param [ String | Symbol ] name The name of the client to set. @param [ Mongo::Client ] client The client to set.

@return [ Mongo::Client ] The set client.

# File lib/mongoid/clients.rb, line 95
def set(name, client)
  clients[name.to_sym] = client
end
with_name(name) click to toggle source

Get a stored client with the provided name. If no client exists with the given name, a new one will be created, stored, and returned.

@example Get a client with the name.

Mongoid::Clients.with_name(:replica)

@param [ String | Symbol ] name The name of the client.

@return [ Mongo::Client ] The named client.

# File lib/mongoid/clients.rb, line 75
def with_name(name)
  name_as_symbol = name.to_sym
  return clients[name_as_symbol] if clients[name_as_symbol]
  CREATE_LOCK.synchronize do
    if (key_vault_client = Mongoid.clients.dig(name_as_symbol, :options, :auto_encryption_options, :key_vault_client))
      clients[key_vault_client.to_sym] ||= Clients::Factory.create(key_vault_client)
    end
    clients[name_as_symbol] ||= Clients::Factory.create(name)
  end
end