Module: Switchman::ActiveRecord::TestFixtures

Defined in:
lib/switchman/active_record/test_fixtures.rb

Constant Summary collapse

FORBIDDEN_DB_ENVS =
%i[development production].freeze

Instance Method Summary collapse

Instance Method Details

#enlist_fixture_connectionsObject



37
38
39
40
41
42
43
# File 'lib/switchman/active_record/test_fixtures.rb', line 37

def enlist_fixture_connections
  setup_shared_connection_pool

  ::ActiveRecord::Base.connection_handler.connection_pool_list.reject do |cp|
    FORBIDDEN_DB_ENVS.include?(cp.db_config.env_name.to_sym)
  end.map(&:connection)
end

#setup_fixtures(config = ::ActiveRecord::Base) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/switchman/active_record/test_fixtures.rb', line 7

def setup_fixtures(config = ::ActiveRecord::Base)
  super

  return unless run_in_transaction?

  # Replace the one that activerecord natively uses with a switchman-optimized one
  ::ActiveSupport::Notifications.unsubscribe(@connection_subscriber)
  # Code adapted from the code in rails proper
  @connection_subscriber =
    ::ActiveSupport::Notifications.subscribe("!connection.active_record") do |_, _, _, _, payload|
      spec_name = payload[:spec_name] if payload.key?(:spec_name)
      shard = payload[:shard] if payload.key?(:shard)
      setup_shared_connection_pool

      if spec_name && !FORBIDDEN_DB_ENVS.include?(shard)
        begin
          connection = ::ActiveRecord::Base.connection_handler.retrieve_connection(spec_name, shard: shard)
        rescue ::ActiveRecord::ConnectionNotEstablished, ::ActiveRecord::NoDatabaseError
          connection = nil
        end

        if connection && !@fixture_connections.include?(connection)
          connection.begin_transaction joinable: false, _lazy: false
          connection.pool.lock_thread = true if lock_threads
          @fixture_connections << connection
        end
      end
    end
end