class ActiveRecord::Middleware::DatabaseSelector

for Time.
‘require “active_support/core_ext/integer/time”` to load the libraries
Note: If you are using `rails new my_app –minimal` you will need to call
config.active_record.database_resolver_context = MyResolver::MySession
config.active_record.database_resolver = MyResolver
config.active_record.database_selector = { delay: 2.seconds }
custom class:
The default behavior can be changed by setting the config options to a
any other config file loaded on boot.
Alternatively you can set the options in your environment config or
end
config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
config.active_record.database_selector = { delay: 2.seconds }
Rails.application.configure do
following contents:
This will create a file named config/initializers/multi_db.rb with the
bin/rails g active_record:multi_db
run the provided generator.
To use the DatabaseSelector in your application with default settings,
replica.
that informs the application when to read from a primary or read from a
Rails default middleware uses the request’s session to set a timestamp
decide when to switch.
resolver context class that sets a value that helps the resolver class
from the primary if a write occurred less than 2 seconds ago) and a
The resolver class defines when the application should switch (i.e. read
behavior.
applications to write custom strategy classes to override the default
provides a basic framework to determine when to swap and allows for
swapping from the primary to the replica database connection. Rails
The DatabaseSelector Middleware provides a framework for automatically

def call(env)

database application.
Middleware that determines which database connection to use in a multiple
def call(env)
  request = ActionDispatch::Request.new(env)
  select_database(request) do
    @app.call(env)
  end
end

def initialize(app, resolver_klass = nil, context_klass = nil, options = {})

def initialize(app, resolver_klass = nil, context_klass = nil, options = {})
  @app = app
  @resolver_klass = resolver_klass || Resolver
  @context_klass = context_klass || Resolver::Session
  @options = options
end

def reading_request?(request)

def reading_request?(request)
  request.get? || request.head?
end

def select_database(request, &blk)

def select_database(request, &blk)
  context = context_klass.call(request)
  resolver = resolver_klass.call(context, options)
  response = if reading_request?(request)
    resolver.read(&blk)
  else
    resolver.write(&blk)
  end
  resolver.update_context(response)
  response
end