ruby script - how to write one that deals with different environment?

hi guys,

I would like to write a script that is runned by cron. It will update
multiple entries.

Any guides for this?
I can't figure out how do we choose which ruby environment (ie.
development/test/production) in the script
and also, how do I access models in the script (which is also used by
my rails application)?


The easiest way may be to have a class with a class method, e.g.

class FooRunner




And then call:

/path/to/my/app/script/runner -e production

from Cron.



All you need is access to the RAILS_ENV constant. For example this script

– x.rb–


Cool but how abt accessing the models? Andy gave a solution but i want
to see what others think

You should just be able to access the models normally (i.e. just use the class, without needing to require anything) if you’re using script/runner.

If you want to do it with a raw Ruby script (rather than using script/runner), you’ll have to include RubyGems, ActiveRecord and point ActiveRecord at the database.yml section, load all the models found below the specific part.

To be honest, it’s much easier just to use script/runner.



If you use script/runner then just use them as you normal would.

Scripts run from script/runner run as normal rails application so all the same setup that the web application has will be provided for your script.

hi, Andy and Peter,
Thanks for the feedback :slight_smile:
i will try it out :slight_smile:

Gordon Yeong

If you use script/runner then just use them as you normal would.

Just out of curiosity couldn't you just to a rake task instead and call
that from cron?

guys, in addition to Peter’s reply, here’s a good reference for script/runner.

If you set up a rake task in lib/tasks/your_cron_job.rake with
something like this

namespace :your_cron_job do
   desc "describe the task"
   task :every_five_minutes => :environment do
       @post =

you can add it manually to the cron by typing 'crontab -e' which opens
the file for editing (*nix only)
crontab -e

first specify how often you want the job to run... in this case every
5 minutes "*/5 * * * *" along with correct paths to app and rake, set
the RAILS_ENV and task name to execute. Cron is just a file so you'll
enter all the info for the job on one line like so... (if you don't
have a default editor set up already it will prompt you to do so
before entering in this command).

*/5 * * * * cd /var/www/my_ror_application && /usr/bin/rake
RAILS_ENV=production your_cron_job:every_five_minutes

More info here
There are more elegant approaches to this problem. This is just the
quick and dirty.

hi there, bseanvt,

   The thought of using the rake task is good but it's not applicable
to my situation whereby I am just running this script after each run
of thinking_sphinx:index which takes place every 20 mins.