How can I set the Rails environment for my somewhat stand alone Ruby script? How can I set the Rails environment for my somewhat stand alone Ruby script? ruby ruby

How can I set the Rails environment for my somewhat stand alone Ruby script?


If you're going to be using the rails environment, your best bet would be to make this a rake script. To do this, put a twitter.rake file into lib/tasks and begin and end it like this:

task(:twitter_load => :environment) do  # your code goes hereend

That way, you're doing it by "following conventions" and it doesn't have that 'orrible smell associated with it.


I currently use the following method, and I know the environment doesn't have the rb extension, it's not needed. You can also set it before running it to overwrite the ENV["RAILS_ENV"].

#!/usr/bin/env ruby# Set your environment here.ENV["RAILS_ENV"] ||= "production"require File.dirname(__FILE__) + "/../../config/environment"puts "Rails was loaded!"

Then to change the environment, just run it with:

rb /lib/tasks/file.rb RAILS_ENV=development


Don't forget script/runner.

Set your environment variable from the command line and

ruby script/runner your_script_here.rb