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
  begin
    dbh = Mysql.real_connect(config["host"],
      config["username"], config["password"], config["database"])
    ActiveRecord::Base.establish_connection config
    yield
  ensure
    dbh.close unless dbh.nil?
  end
end

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(File.open(filename))
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

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>