Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 540
Nick Messick Avatar asked Feb 09 '09 19:02

Nick Messick


People also ask

How do I create an environment variable in Ruby?

Ruby has direct access to environment variables via the ENV hash. Environment variables can be directly read or written to by using the index operator with a string argument. Note that writing to environment variables will only have an effect on child processes of the Ruby script.

What is the default Rails environment?

When we generate a new Rails application we get three environments by default: development , test and production . There's nothing special about these particular environments, though, and there are very few places in the Rails source code that refer to them.

How do I run a Ruby on Rails script?

The simplest way is with rails runner because you don't need to modify your script. runner runs Ruby code in the context of Rails non-interactively. If you make the script executable by running chmod +x script. rb , you can add #!/usr/bin/env rails runner to the top of the script, and then simply run it with ./script.


1 Answers

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.

like image 157
Ryan Bigg Avatar answered Oct 29 '22 19:10

Ryan Bigg