Wednesday, April 09, 2008

ActiveRecord Without Rails, Refined

About a year ago Aizat Faiz, a software developer in Malaysia wrote a blog entry about using ActiveRecord outside of the Rails framework. This is definitely something that I want to do for a variety of reasons, the simplest being that I'd like to write utility programs that access the database without needing to also write a user interface for them.

In any case, Aizat wrote a nice understandable entry. However, he seemed to make the assumption that developers using ActiveRecord without Rails would not have a Rails application at all. This is not the case for me.

If your utility script resides in the top level directory, then you can use your already existing database.yml file instead of creating a new one. Just use the following as a guide.

dbconfig = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(dbconfig['development'])

Also, there is no reason to have your models in your script when they are already in your Rails application. You can load existing modesl like this:

require 'app/models/event.rb'
require 'app/models/senator.rb'

That's it. Very simple and no duplication of code.

Post a Comment