Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strategies for overriding database.yml?

Tags:

In my environment, the deployment servers have much of the connection information that is in the database.yml. That is, they know whether they are development, test or production servers, and they know their respective database connection information.

I can encapsulate this information in a Server class for example, so that I can retrieve the information:

Server["environment"] #=> production Server["db_host"] #=> db5.example.com Server["db_password"] #=> [a decrypted password] 

and so on. I would like to deploy a Rails application and have it autoconfigure based on the Server settings. What is the best way to do this?

One way to do this is Erb in my database.yml:

<%= Server["environment"] %>:    adapter: oracle_enhanced   host: <%= Server["db_host"] %>   username: db_user    password: <%= Server["password"] %> 

I'm not too thrilled about doing it this way, but it would work. In this case, where would I put the 'server.rb' that defines the Server class--require it here in the yml? app/initializers gets loaded after ActiveRecord loads database.yml.

Another possible solution is to somehow override railties' database initializer:

# File railties/lib/initializer.rb, line 903 def database_configuration   require 'erb'   YAML::load(ERB.new(IO.read(database_configuration_file)).result) end 

The above is called only if :active_record is defined in config.frameworks. I'm not sure how I would go about overriding this early enough in the Rails startup sequence.

Maybe a third option is to remove :active_record from config.frameworks, and then create the connection later, say in the app initializers? I'm afraid this may have lots of unintended side effects.

I'm hoping that there's something simple and obvious that I haven't found, such as an ActiveRecord feature that allows me to opt out of database.yml and provide alternate config programmatically.

like image 669
Mark Thomas Avatar asked Nov 17 '10 13:11

Mark Thomas


1 Answers

You can provide your own database customizations directly in your application.rb: It seems to work nice rails 3.2. (Be warned though, it's a kind-of monkey patching)

module MyApp    class Application < Rails::Application     # ... config      config.encoding = "utf-8"       def config.database_configuration       parsed = super       raise parsed.to_yaml  # Replace this line to add custom connections to the hash from database.yml     end   end end 
like image 68
gamecreature Avatar answered Oct 29 '22 11:10

gamecreature