Ruby-on-rails – How to set the Rails environment for the somewhat stand alone Ruby script

rubyruby-on-rails

I have a Ruby script in my Rails app that I use to load some data from Twitter.

In the future I will make it an automatic background process, but for now I run it manually like:

ruby /lib/twitter/twitterLoad.rb

In order to use the Rails model classes and such, I have the following as the top line of the script:

require "#{File.dirname(__FILE__)}/../../config/environment.rb"

By default, the development environment is used. But, I'd like to be able to choose the production environment at some point.

Update #1: The RAILS_ENV constant is getting set in the environment.rb file. So, I was able to put ENV['RAILS_ENV'] = 'production' at the very top (before the environment.rb) line and solve my problem somewhat. So, my new question is, can do pass in env vars through the command line?

Best Answer

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 here
end

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