Monday, July 27, 2009

ActiveRecord outside of Rails (even with ODBC)

There are three quick lines that you need in order to use ActiveRecord outside of Rails. First, you need to load gems, then you can load ActiveRecord. Then, you can pick and choose which of your models to use.


require 'rubygems'
require 'activerecord'
require @@RAILS_APP_HOME + '/app/models/foo.rb'


Then, you'll need this little snippet to establish the connection to the database for ActiveRecord:

require 'rubygems'
require 'activerecord'
require 'yaml'

@@DATABASE_CONFIGURATION = YAML::load(File.open(File.dirname(__FILE__) + '/config/databases.yml'))

def establish_connection(database)
dbconfig = @@DATABASE_CONFIGURATION
ActiveRecord::Base.establish_connection(dbconfig[database])
# ActiveRecord::Base.logger = Logger.new(STDERR)
if (dbconfig['mode'] == 'odbc')
puts("Connecting to [#{database}]: ODBC,"+
" DSN=#{dbconfig[database]['dsn']}/#{dbconfig[database]['adapter']}"+
" [user=#{dbconfig[database]['username']}]")
else
puts("Connecting to [#{database}]: #{dbconfig[database]['adapter']}, "+
"#{dbconfig[database]['database']}@#{dbconfig[database]['host']}"+
" [user=#{dbconfig[database]['username']}]")
end
end

def remove_connection
ActiveRecord::Base.remove_connection
end
~


I put the above snippet in a central ruby file, then require that file anywhere I need to use the ActiveRecord objects. After a call to establish_connection, you can start using any model you've imported. Note, you'll see a slightly different URL constructed for ODBC.

No comments: