in

 

Chad Myers' Blog

Department of Problem Prevention

Working with ActiveRecord model classes outside of the Rails environment

I had a task yesterday that involved me wanting to dump some information about a Rails ActiveRecord class I had (don't ask, it's a long story).

I wanted to access my AR class from outside the Rails web environment (i.e. I wanted to type 'ruby something' from the command line).

I put a file in the scripts folder and put the following code at the top:

ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'development'
RAILS_ROOT = "#{File.dirname(__FILE__)}/.." unless defined?(RAILS_ROOT)
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(YAML::load(File.open('config/database.yml'))[ENV['RAILS_ENV']])

From here on out, you have the basics of the rails environment and can execute ActiveRecord functionality.

Published Jan 06 2008, 08:27 AM by chadmyers
Filed under: ,

Comments

 

Mike Breen said:

What about creating a rake task? Then you could just type 'rake something''?

January 6, 2008 8:58 AM
 

chadmyers said:

I hadn't got that far yet, I wanted to be able to do it first before automating it. This was the first day I had done any Ruby at all, so take it easy on me :)

January 6, 2008 9:12 AM
 

Mike Breen said:

When you're ready to write a custom rake task you should check out this tutorial: www.railsenvy.com/.../ruby-on-rails-rake-tutorial

Good luck!

January 6, 2008 9:27 AM
 

Mike Breen said:

I also like to think of rake as a tool for "heavy lifting" in Rails, not just automation. Getting at the Rails environment is easy enough:

task(:my_task => :environment) do

 #work with you AR here

end

But I'm not sure what you're trying to accomplish so maybe rake won't help you here.

January 6, 2008 9:58 AM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About chadmyers

Chad Myers is a senior .NET software developer specializing in enterprise software designs and architectures. He has over 10 years of software development experience and a proven track record of Agile, test-driven project leadership using both Microsoft and open source tools. He is community leader who speaks at the Austin .NET User's Group, the ADNUG Code Camp, and participates in various development communities and open source projects.
Copyright Los Techies 2007. All rights reserved.
Powered by Community Server (Commercial Edition), by Telligent Systems