Ruby: Active Record without Rails
For a few years now I am a huge fan of Rails. Rails again introduced me to Ruby, which is really the coolest scripting language ever.
I am using Rails for several Web-Interfaces, both at kooaba and in my research. Currently I am working on some massively distributed processing, which requires access to the relational databases but no interface. So I started using Ruby with Active Record without Rails. Here are some learnings to make it work:
Basic usage:
#!/usr/bin/env ruby
require 'rubygems'
require 'active_record'
require 'logger'
ActiveRecord::Base.establish_connection(
:adapter => 'mysql',
:database => 'db',
:username => 'johndoe',
:password => 'ggrrr',
:host => 'some.host.com')
ActiveRecord::Base.logger = Logger.new("mylog.log")
ActiveRecord::Base.table_name_prefix="pf_"
Problems really started when using the table prefix. Now you want to add your models you are also using in Rails - it turns out you have to add them AFTER the code above, otherwise the prefix is not added to many-to-many relationship tables. No idea why, but it’s the way it is, at least in Rails 1.3.
So, add your models (after the segment above) like this:
require 'mymodel.rb' require 'anothermodel.rb'
That’s it, you’re ready to roll.
Some more background: I am calling instances of may ruby scripts with condor. Defining a logfile (logger) as above helps debugging later.