Skip to content

Instantly share code, notes, and snippets.

@limhoff-r7
Created May 30, 2014 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save limhoff-r7/71ee6b1568b604e131a8 to your computer and use it in GitHub Desktop.
Save limhoff-r7/71ee6b1568b604e131a8 to your computer and use it in GitHub Desktop.
ActiveRecord::Base.establish_connection doesn't actually test that your connection spec can connect to the database. You need to ask for a connection to test that explicitly.
ActiveRecord::Base.establish_connection
# Check if the spec passed to `ActiveRecord::Base.establish_connection` can connect to the database.
#
# @return [true] if an active connection can be made to the database using the current config.
# @return [false] if an active connection cannot be made to the database.
def connection_established?
begin
# use with_connection so the connection doesn't stay pinned to the thread.
ActiveRecord::Base.connection_pool.with_connection {
ActiveRecord::Base.connection.active?
}
rescue PG::ConnectionBad => error
false
end
end
ActiveRecord::Base.establish_connection
ActiveRecord::Base.connected? # false
ActiveRecord::Base.connection.active? # true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment