如何使用sidekiq在后台运行方法?目前我有这样的事情:
order.rb
class Order < ActiveRecord::Base
include Badges
belongs_to :user
end
顾虑/ badges.rb
module Badges
extend ActiveSupport::Concern
included do
after_update :badges
end
def badges
streak = user.selling_streak.value
case streak
when 3
user.add_badge(5) unless user.badges.any? {|b| b.id == 5}
when 5
user.add_badge(6) unless user.badges.any? {|b| b.id == 6}
end
end
end
我已经将徽章方法置于关注状态,它将在订单模型中的after_update回调上运行。如何将整个方法与sidekiq一起放在后台进程中?
答案 0 :(得分:0)
在你的应用程序中使用sidekiq非常简单。它基本上只是跟随examples from the sidekiq website和copy'n'粘贴你的代码:
更改concers/badges.rb
以生成sidekiq作业:
module Badges
extend ActiveSupport::Concern
included do
after_update :assign_badges
end
def assign_badges
BadgesAssignment.perform_async(user.id)
end
end
创建一个sidekiq工人类:
class BadgesAssignment
include Sidekiq::Worker
def perform(user_id)
user = User.find_by(id: user_id)
if user
streak = user.selling_streak.value
case streak
when 3
user.add_badge(5) unless user.badges.any? {|b| b.id == 5}
when 5
user.add_badge(6) unless user.badges.any? {|b| b.id == 6}
end
end
end
end