If you have done a good job of building your rails models, you may find that they are helpful for your non-rails system maintenance and such. They may even be necessary to reuse if you follow the rails model of using activerecord validations (rather that database RI) to preserve the integrity of your data.

Or you may just find yourself rewriting the same code again and again, and want all that good railsiness to make it easier to write and maintain. Personally I find myself in some instance of ./script/console as often as irb just so I can get the activesupport helper methods ( 4.days.from_now and such) that many rails developers are surprised to find are not actually a standard part of ruby.

So, the good news is it is easy to reuse rails code outside of rails.

Let’s say you want to do some data manipulation (reporting, loading, scrubbing, etc) in your rails db, and want to use your models to do it. A few imports in your ruby script gets the necessary environment in place:

require ‘rubygems’
require ‘yaml’
require ‘active_record’
require ‘logger’

and a few more will load up your models (note: they’re probably not in the same location as mine, unless you are also working on an app called ‘seweb’ in your home dir):

PROJECT_HOME = "#{ENV['HOME']}/seweb/"
require "#{PROJECT_HOME}/app/models/sales_rep.rb"
require "#{PROJECT_HOME}/app/models/organization.rb"
require "#{PROJECT_HOME}/app/models/team.rb"

Then connect to the appropriate database (note I’m connecting to the development environment – can you guess how I’d connect to ‘test’ or ‘production’?), with rails logging enabled:

ActiveRecord::Base.logger = Logger.new( STDERR )
db_config = YAML::load( File.open("#{seweb_home}/config/database.yml"))
ActiveRecord::Base.establish_connection( db_config["development"])

And you are good! If you are using a transactional database (such as my personal favorite, MySQL with InnoDB), you can make nice transaction wrappers for your work thusly:

ActiveRecord::Base.transaction do

        rep = SalesRep.find_or_initialize_by_name( ‘Kyllin D. Quota’ )
        # create the component parts
        if( rep.changed? )
            rep.organization = Organization.find_or_create_by_name ‘APAC’
            rep.team = Team.find_or_create_by_name ‘Enterprise’

        rescue Exception
            raise ActiveRecord::Rollback, "Invalid record for #{rep.name}"


Pow. You get your rails sugar, rails validations, rails logging. Are you happy? Why yes, yes you are.