将ActiveRecord的数据加载到Capistrano的deploy.rb

时间:2012-11-12 14:59:10

标签: ruby-on-rails capistrano sidekiq

我使用Capistrano进行部署,使用Sidekiq进行队列。我需要加载用户id以在deploy.rb文件中设置:sidekiq_queues变量来执行sidekiq队列。现在我使用以下代码

set :sidekiq_queues, ::User.all.map {|u| "-q parsing_user_#{u.id}"}.join(" ") + " -q parsing_user_0"

但它会抛出以下错误

./config/deploy.rb:29:in `load': uninitialized constant User (NameError)

我试图在deploy.rb中要求'rubygems'和'active_record',但它没有帮助。 结果我应该有     sidekiq_queues ==“ - q parsing_user_1 -q parsing_user_2 -q parsing_user_3 -q parsing_user_4 -q parsing_user_5 -q parsing_user_0”。 硬编码队列名称不是解决方案。

1 个答案:

答案 0 :(得分:1)

Capistrano在本地执行deploy.rb,并且它不会在deploy.rb中加载您的Rails环境。

它可能比它的价值更麻烦。特别是如果要在远程服务器上执行此操作,可以考虑执行Rake任务。 rake任务中的=> :environment可确保加载Rails环境。

# in deploy.rb
namespace :sidekiq do
  desc "Do something with queues"
  task :queues, :roles => :web  do
    run "cd #{current_path} ; RAILS_ENV=#{rails_env} bundle exec rake sidekiq:queues"
  end
end

# you'll need to decide when to execute this in your deployment process, 
# something like this:

after "deploy:update_code", "sidekiq:queues"



# in lib/tasks/sidekiq.rake
namespace :sidekiq do
  desc "Do something with queues"
  task :queues => :environment do
    queues = (User.scoped.pluck(:id) + [0]).map{|id| "-q parsing_user_#{id}"}.join(" ")
    # do what you need to do
  end
end