Basic tech stuff

Programming and Linux administration

Standalone code using a Rails database

Posted by Daniel Brahneborg on 2007 February 22

I’m using a Rails application to update a database, but I also want to run an external program on that database once in a while. While it might be done by creating a new thread within the Rails application, I wanted a standalone program. However, it should still use the same database configuration, Ruby models, etc.

First I need to load the Mysql driver, YAML parser, and ActiveRecord:

require 'yaml'
require 'rubygems'
require_gem 'mysql'
require_gem 'activerecord'

Then the load path for ‘require’ must be extended to include my models:

$: << File.join(File.dirname(__FILE__), '../../app/models')

To connect to the database, make sure ActiveRecord uses this connection, and that it gets closed afterwards, I use code like this. The application code is sent as a block.

def with_database(config)
  dbh = nil
    dbh = Mysql.real_connect(config["host"],
      config["username"], config["password"], config["database"])
    ActiveRecord::Base.establish_connection config
    dbh.close unless dbh.nil?

First I load the database config. The “development” profile is hard coded, but could easily be changed into using an environment variable or something.

filename = File.join(File.dirname(__FILE__), '../../config/database.yml')
dbconfig = YAML.load(
dev = dbconfig["development"]

Then I can run the application code:

with_database(dev) {
# yadda yadda

When the function completes, either normally or by raising an exception, the database is closed.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: