ActiveRecord outside of Rails (and YAML)
Written on July 16, 2008 by george
Lately I’ve been working on a stock trading program that automatically trades and saves the results to a database (more details to follow in the not too distant future…) Naturally the choice of language was ruby, and for the front end, a rails application. Once coded, I bundled the stock trading program into the rails lib folder and reused the rails model for saving to the database.
I ran into a slight problem doing this though as ActiveRecord needs configuring manually outside the rails framework but I wanted to follow best practices and keep my code DRY. After a quick search I found a clean solution that allows you to re-use the database.yml configuration file from the rails application:
dbconfig = YAML::load(File.open('config/database.yml'))
ActiveRecord::Base.establish_connection(dbconfig["development"])
This snippet got me thinking about YAML which I use a lot but have never played with in Ruby. It turns out the YAML class is basically a hash that uses strings (gotcha not keys) to access a simple hierarchy:
dbconfig = YAML::load(File.open('config/database.yml'))
dbconfig["development"]["adapter"] # = mysql
All very simple stuff but if its never crossed your mind before, you yet again appreciate the elegance of ruby.
If you enjoyed this post Subscribe to our feed



