Module: Whodunit::Chronicles::AdapterLoader

Defined in:
lib/whodunit/chronicles/adapter_loader.rb

Overview

Lazily loads the correct database adapter gem at runtime.

This avoids forcing all users to install both pg and trilogy regardless of which database they actually use.

Examples:

adapter = AdapterLoader.load(:postgresql)
adapter = AdapterLoader.load(:mysql)
adapter = AdapterLoader.load(:mariadb)

Constant Summary collapse

ADAPTER_REGISTRY =

Map of adapter type symbols to their required gem and class path.

{
  postgresql: {
    gem: 'pg',
    require: 'whodunit/chronicles/adapters/postgresql',
    class: 'Whodunit::Chronicles::Adapters::PostgreSQL',
    hint: "Add `gem 'pg', '~> 1.5'` to your Gemfile.",
  },
  mysql: {
    gem: 'trilogy',
    require: 'whodunit/chronicles/adapters/mysql',
    class: 'Whodunit::Chronicles::Adapters::MySQL',
    hint: "Add `gem 'trilogy', '~> 2.9'` to your Gemfile.",
  },
  mariadb: {
    gem: 'trilogy',
    require: 'whodunit/chronicles/adapters/mysql',
    class: 'Whodunit::Chronicles::Adapters::MySQL',
    hint: "Add `gem 'trilogy', '~> 2.9'` to your Gemfile.",
  },
}.freeze

Class Method Summary collapse

Class Method Details

.load(type) ⇒ Adapters::Base

Load and instantiate an adapter by type.

Parameters:

  • type (Symbol)

    one of :postgresql, :mysql, :mariadb

  • options (Hash)

    options forwarded to the adapter constructor

Returns:

  • (Adapters::Base)

    the instantiated adapter

Raises:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/whodunit/chronicles/adapter_loader.rb', line 44

def self.load(type, **)
  config = ADAPTER_REGISTRY[type.to_sym]

  unless config
    known = ADAPTER_REGISTRY.keys.map(&:inspect).join(', ')
    raise ConfigurationError,
      "Unknown adapter type #{type.inspect}. Known adapters: #{known}"
  end

  load_gem!(config)
  require config[:require]
  Object.const_get(config[:class]).new(**)
rescue LoadError => e
  raise AdapterLoadError,
    "Could not load the '#{config[:gem]}' gem required for the " \
    "#{type} adapter.\n#{config[:hint]}\nOriginal error: #{e.message}"
end

.load_gem!(config) ⇒ Object (private)

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



63
64
65
# File 'lib/whodunit/chronicles/adapter_loader.rb', line 63

def self.load_gem!(config)
  require config[:gem]
end