require "rubygems" require_gem "activerecord"
and then include a call to establish_connection to connect to the database.
At this point, I’m up and running, and I can play with all the Active Record functionality. But… I still wanted to create tables in the underlying database. In the first edition, I used DDL to do this, but in the second I wanted to use migrations.
My first hack was to use the fact that the various schema definition methods are defined both for migrations and in every database connection object. That let me use the following in my code:
ActiveRecord::Base.connection.instance_eval do create_table children, :force => true do |t| t.column :parent_id, :integer t.column :name, :string t.column :position, :integer end end
I was pretty chuffed with this until Jamis Buck (who else) pointed out a more elegant way:
ActiveRecord::Schema.define do create_table children, :force => true do |t| t.column :parent_id, :integer t.column :name, :string t.column :position, :integer end end
As I see more and more people start to use Ruby (and Active Record) as enterprise glue, being able to bring these kinds of Rails goodies to non-Rails applications is a win all around.