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.

What I do (with spoilers)