Anyone who has even the smallest amount of experience developing with Ruby on Rails knows that Rails has some pretty sweet configuration conventions which make switching between environments very easy. Switching from development to production to testing is as easy as changing the RAILS_ENV variable. No doubt Rails does some dark magic behind the scenes to trivialise this. But what if you’re writing an app in Ruby, without the Rails to guide you?
Establishing a database connection in ActiveRecord without Rails is pretty basic:
It establishes a connection to the specified database with the specified connection configuration. If you were using MySQL or PostgreSQL you would provide the relevant configuration such as username, password and host. With the connection established, we can now start consuming the connection however we like. For example, we may want to use funky Rails’ style models (so we can easily create and populate tables and reference them):
create_table :things do |t|
t.integer :id, :null => false
class Thing < ActiveRecord::Base
Care about the Environment
The other magic in Rails is the environment selection. The main benefit with this is that we can have isolated connection configurations and have our Ruby app automatically select the correct settings for us (using our environment variable ENV).
conf = case ENV['DB']
raise 'export DB=conf[n]'
Mind you, before this will work you first need to set the environment variable:
export DB=conf1 # or conf2
Now, depending on ENV[‘DB’], the code will open a connection to the corresponding database.
It’s never a good idea to store sensitive information (like database connection information and usernames and password of any kind) in your code base. Rails uses an external database configuration file called database.yml to solve this problem, so lets implement one ourselves.
Loading this YAML file is very simple:
conf = YAML.load_file('database.yml')
Now we can set our environment variable same as before, but our code will look in a YAML file for the proper database configuration automatically, without having to store database connection information directly inside our code.