无法将params传递给sidekiq

时间:2015-02-17 16:01:58

标签: ruby-on-rails ruby redis sidekiq

我正在为控制器操作构建一个worker,但是由于我在perform方法中调用了params,所以sidekiq无法启动。关于如何使其发挥作用的任何想法?

控制器

def call_warrants_with_date_range
  CallLogWorker.perform_async(params[:call_log])
  redirect_to call_logs_path, notice: 'Calls were successfully made.'
end

工人

class CallLogWorker
  include Sidekiq::Worker

  def perform(params[:call_log])
    client         = Twilio::REST::Client.new TWILIO_ACCOUNT_SID, TWILIO_ACCOUNT_AUTH_TOKEN
    start_date         = params[:call_log][:warrant_start_date]
    end_date           = params[:call_log][:warrant_end_date]
    query = "SELECT people.id, warrants.warn_type, warrants.warn_date_issued, phone_numbers.phone_number 
    FROM people
    LEFT OUTER JOIN warrants ON people.id = warrants.person_id
    LEFT OUTER JOIN phone_numbers ON people.id = phone_numbers.person_id
    WHERE warrants.warn_date_issued BETWEEN ? AND ? AND warrants.warn_type = 'AW'"

    @numbers = CallLog.find_by_sql(["#{query}", start_date, end_date])
    @numbers.each do |dial|
      begin
       call = client.account.calls.create(
       :from => TWILIO_PHONE_NUMBER,
       :to => dial.phone_number,
       :url => 'http://twimlets.com/echo?Twiml=hello%20this%20is%20a%20test%20call%20please%20hang%20up&'
      )

       CallLog.create!({ phone: dial.phone_number, status: call.status, 
       warrant_start_date: start_date, warrant_end_date: end_date, person_id: dial.id})
       Note.create!({ body: call.status, person_id: dial.id })
    rescue Exception => e
       CallLog.create!({ phone: dial.phone_number, status: call.status, exception: e.to_s,
       warrant_start_date: start_date, warrantend_date: end_date, person_id: dial.id})
       Note.create!({ body: e.to_s, person_id: dial.id })
    end
  end
 end
end

1 个答案:

答案 0 :(得分:7)

在你的工人中:

def perform(params)
   start_date         = params[:call_log][:warrant_start_date]
   end_date           = params[:call_log][:warrant_end_date]
   ...etc
end

然后在你的控制器中:

CallLogWorker.perform_async(params)

所以你要从控制器中将哈希参数解析为worker,然后在你的worker中引用它。

通常认为将传递给Sidekiq作业的数据尽可能小 - see here以获得最佳做法是一种很好的做法。所以你可以走得更远:

在你的工人中:

def perform(start_date, end_date)
   ...job content
end

在你的控制器中:

CallLogWorker.perform_async(
  params[:call_log][:warrant_start_date],  
  params[:call_log][:warrant_end_date]
)