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.

2 comments:

peterjohn said...

Pretty good post. I just came across your site and wanted to say that I’ve really enjoyed reading your posts. In any case I’ll be subscribing to your feed and I hope you will keep a good work!Cheer!

sap online training
software online training
sap sd online training
hadoop online training
sap-crm-online-training

peterjohn said...

This is one awesome blog article. Much thanks again.
I really enjoy the blog.Much thanks again. Really Great.


oracle online training
sap fico online training
dotnet online training
qa-qtp-software-testing-training-tutorial