diff --git a/lib/apartment/railtie.rb b/lib/apartment/railtie.rb index 04af0c96..31097cf2 100644 --- a/lib/apartment/railtie.rb +++ b/lib/apartment/railtie.rb @@ -24,26 +24,34 @@ class Railtie < Rails::Railtie ActiveRecord::Migrator.migrations_paths = Rails.application.paths['db/migrate'].to_a end - # Hook into ActionDispatch::Reloader to ensure Apartment is properly initialized - # Note that this doens't entirely work as expected in Development, because this is called before classes are reloaded - # See the middleware/console declarations below to help with this. Hope to fix that soon. - # + # Make sure Apartment is reconfigured when the code is reloaded + config.to_prepare do - next if ARGV.any? { |arg| arg =~ /\Aassets:(?:precompile|clean)\z/ } - next if ARGV.any? { |arg| arg == 'webpacker:compile' } + ActiveRecord::Base.reinitialize_apartment + end - begin - Apartment.connection_class.connection_pool.with_connection do - Apartment::Tenant.init - end - rescue ::ActiveRecord::NoDatabaseError, PG::ConnectionBad - # Since `db:create` and other tasks invoke this block from Rails 5.2.0, - # we need to swallow the error to execute `db:create` properly. - Rails.logger.warn do - 'Failed to initialize Apartment because a database connection could not be established.' + # + # Ensure that Apartment::Tenant.init is called when + # a new connection is requested. + # + module ApartmentInitializer + def connection + super.tap do + unless @apartment_already_initialized + # To avoid infinite loops in work init is doing, + # we need to set @apartment_already_initialized to true + # before init is called + @apartment_already_initialized = true + Apartment::Tenant.init + end end end + + def reinitialize_apartment + @apartment_already_initialized = false + end end + ActiveRecord::Base.singleton_class.prepend ApartmentInitializer # # Ensure rake tasks are loaded diff --git a/spec/examples/generic_adapter_examples.rb b/spec/examples/generic_adapter_examples.rb index bc0b1390..1a8b44d4 100644 --- a/spec/examples/generic_adapter_examples.rb +++ b/spec/examples/generic_adapter_examples.rb @@ -25,7 +25,7 @@ .instance_variable_get(:@queue) .size - expect(num_available_connections).to eq(1) + expect(num_available_connections).to eq(0) end end end