How to detect Rails environment inside whenever

Marius Butuc picture Marius Butuc · Aug 16, 2011 · Viewed 12.1k times · Source

This question will probably only make sense if you know about the whenever gem for creating cron jobs.

For my app, I want to use whenever in all the environments, including testing and development.
My schedule.rb looks like this:

set :output, {
    :error    => "#{path}/log/error.log",
    :standard => "#{path}/log/cron.log"
}

set :environment, Rails.env.to_sym
every 5.minutes do
  rake 'db:activity:synchronize'
end

but it fails on Rails.env.to_sym (and the same stands for RAILS_ENV):

/home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `eval': uninitialized constant Whenever::JobList::Rails (NameError)
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `eval'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/job_list.rb:21:in `initialize'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever.rb:15:in `new'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever.rb:15:in `cron'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/command_line.rb:41:in `run'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/lib/whenever/command_line.rb:8:in `execute'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/gems/whenever-0.6.8/bin/whenever:38:in `<top (required)>'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/bin/whenever:19:in `load'
    from /home/marius/.rvm/gems/ruby-1.9.2-p290@uxolo/bin/whenever:19:in `<main>'

So, my question basically boils down to:

  1. How do I access the current environment, or
  2. What should I do to use whenever in all the environments?

Answer

Mattias Wadman picture Mattias Wadman · Jan 8, 2012

At least in newer version of whenever it is possible to access the environment with @environment. For example if you want whenever to only generate cron entries for some jobs in production:

case @environment
when 'production'
  every 1.day, :at => '0:00 am' do
    rake "some:task"
  end 
end