Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 23 additions & 15 deletions lib/apartment/railtie.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion spec/examples/generic_adapter_examples.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down