This is a fairly simple little tidbit, but still useful. Sometimes I want to have a script for my rails application, like running some reports on the data. There are two basic ways to do this: write a task(rake), or create a new ruby script file, like in the scripts directory.
If you want to do the latter, then there are two lines you my want to put at the top of your script.
ENV['RAILS_ENV'] = ARGV.first || ENV['RAILS_ENV'] || 'development' require File.expand_path(File.dirname(__FILE__) + "/../config/environment")
The first line allows us to supply which environment we would like to run the script in. Say the script is called process.rb, we could call the script like ./process.rb production and now the environment is set to production.
The second line loads the environment file. Now all of rails, your models, libraries, and plugins are available to you.
October 14th, 2006 at 6:28 pm #Chris
Aaaaand why aren’t you using rake, again?
October 21st, 2006 at 5:13 am #Adam
I would use rake for doing a report or for something that should run once and be done; however, sometimes you may want to run something more intensive, something that you would want to run in the background.
I will say that when I started off, I wrote scripts that really should have been rake tasks, but every now and then a script does the job