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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With