Whenever Gem执行失败求助:bundle exec whenever报错未初始化常量Rails
问题:执行
bundle exec whenever报错未初始化常量Rails 报错信息
$ bundle exec whenever bundler: failed to load command: whenever (/home/cgarndt/.rbenv/versions/3.0.0/bin/whenever) config/schedule.rb:35:in `initialize': uninitialized constant #<Class:#<Whenever::JobList:0x0000555d07619838>>::Rails (NameError) from /home/cgarndt/.rbenv/versions/3.0.0/lib/ruby/gems/3.0.0/gems/whenever-1.0.0/lib/whenever/job_list.rb:25:in `instance_eval' ... ... ...
开发环境配置
- Ubuntu 22.04 LTS
- rbenv
- Ruby 3.0
- Rails 7.0.4
- whenever (1.0.0)
已执行操作及schedule.rb内容
已执行bundle exec wheneverize .生成schedule.rb,内容如下:
# Need the below for Cron to pick up rbenv user version within Unix-user/application. # Vs w/o the below line then Cron uses rbenv system version. env :PATH, ENV['PATH'] # Compare Person API CALS People data to CALS-2 People data if Rails.env.staging? every :monday, at: '7:50am' do runner "CjComparePersApiCalsPeople::Start.execute" end endif ::Rails.env.production? every :monday, at: '8:05am' do runner "CjComparePersApiCalsPeople::Start.execute" end end
解决方案
1. 修复schedule.rb语法错误
原代码中endif ::Rails.env.production?是错误的Ruby语法,可修改为两种形式:
方式一:拆分独立判断
if Rails.env.staging? every :monday, at: '7:50am' do runner "CjComparePersApiCalsPeople::Start.execute" end end if ::Rails.env.production? every :monday, at: '8:05am' do runner "CjComparePersApiCalsPeople::Start.execute" end end
方式二:用elsif简化逻辑
if Rails.env.staging? every :monday, at: '7:50am' do runner "CjComparePersApiCalsPeople::Start.execute" end elsif Rails.env.production? every :monday, at: '8:05am' do runner "CjComparePersApiCalsPeople::Start.execute" end end
2. 加载Rails环境
在schedule.rb开头添加代码,确保whenever能识别Rails常量:
require File.expand_path('../config/environment', __FILE__) # Need the below for Cron to pick up rbenv user version within Unix-user/application. # Vs w/o the below line then Cron uses rbenv system version. env :PATH, ENV['PATH'] # ... 后续原有代码 ...
3. 可选:指定环境执行命令
执行whenever时明确指定环境,确保加载对应配置:
bundle exec whenever -e staging # 或 bundle exec whenever -e production
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

