Archives

Tags

Loading your Rails App independently

Yesterday I found myself in a position where some horrendously ugly code just became too much for me to handle. To cut a long story short, I needed to decouple a custom library from ActiveRecord. How did it get there in the first place, you ask? Please don't. It's a tragic story...

I set up an experimentation environment (in seperation from my working app), but of course, I needed to temporarily have full access to my models, controllers, etc, etc. Now, I use version control (who doesn't?) and I could have simply branched off and started hacking. But for shits-and-giggles, I decided not to.

I played around for a while and, as it turns out, it's very easy to load your application into an otherwise independent Ruby script. All you need is:

ENV['RAILS_ENV'] = 'development'
require '/path/to/your/rails/app/config/environment'

Easy!

As a final note, it's worth pointing out that this is something that you should basically never need to do. If you simply want to automate something or perform an application-specific task, I highly recommend you write a raketask instead.