Access database information at runtime

Hi everyone

Is there a way to access the information in db/database.yml at
runtime. Sort of a DB_ENV or something similar?

Kindest regards

Erik Lindblad

Have you tried RAILS_ENV? It represents the environment in which
you're currently running: development, test or production. Of course,
you can use more or different environments than that by making your
own, e.g., staging.

Regards,
Craig

Hi everyone

Is there a way to access the information in db/database.yml at
runtime. Sort of a DB_ENV or something similar?

This is grungy (because there is no accessor for the instance
variable. might not work for all adapters, might break between rails
versions etc...)

ActiveRecord::Base.connection.instance_variable_get('@config')

If different models have different settings, then say
Person.connection.instance_variable_get('@config')

will get that models configuration

Fred

Great advice, this really works. Craig, thanks for the advice but I
really wanted to get the actual values set in database.yml and not the
environment itself.

Is there a reason for not putting this in RAILS_ENV or any similar
construct? Or is it "un-Raily" to want to know what goes on behind the
curtains.

Great advice though, it will work for now.

Regards

Erik Lindblad

Hi Erik,

Erik Lindblad wrote:

I really wanted to get the actual values set in database.yml

You can do this quite easily by just reading database.yml. Something
like...

db_config =
YAML.load(File.open("#{RAILS_ROOT}/config/database.yml"))[ENV['RAILS_ENV']]

HTH,
Bill

Here's how I can get the username, password, etc from database.yml:

  config = Rails::Configuration.new
  database = config.database_configuration[”production”]

Hope that helps.

ActiveRecord::Base.configurations returns a hash of the known configurations.

ActiveRecord::Base.configurations[‘production’]

=> {“adapter”=>“postgresql”, “host”=>“localhost”, “database”=>“app_production”}

  • Gabriel

Hi all

This last one I think I like the best, more clean.

Thanks for all the input

/Erik