27

I'm trying to run a Ruby script from cron.

The script uses Bundler to manage gem dependencies. Since cron does not run in $PWD I get a 'Could not locate Gemfile' error from Bundler everytime, which makes sense since Gemfile is not in the currrent path when running from cron.

Is there a way to tell Bundler to use a Gemfile not in the current path?

2 Answers 2

42

The best thing to do would be to cd into the directory in question in your cron. You could also use the BUNDLE_GEMFILE environment variable to point at the Gemfile. Please let us know if you have any problems with BUNDLE_GEMFILE.

1
  • Yehuda, thanks I was looking for a env variable to set before calling 'bundle', but I ended up doing "cd /path && bundle exec foo.rb" it is porbably much easier that way.
    – Camilo
    Commented Jul 30, 2010 at 18:08
2

You could have the main script change its dir:

Dir.chdir File.dirname(__FILE__)

You might have to tweak it using File.expand_path to get your app's root dir (where the Gemfile is). Suppose your script is /apps/myapp/bin/main.rb; the chdir line would be:

Dir.chdir File.expand_path('../..', __FILE__)

Of course, you have to make sure your app doesn't break because of the chdir - but it shouldn't if you're cd-ing in the cron.

If the script is a daemon and you want it to be changed to the root dir / during normal operation, you can do that after calling Bundler.setup or Bundler.require.

While you could do cd in the cron, I prefer not to, because crons are already hard enough to read and maintain.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.