Skip to content

Instantly share code, notes, and snippets.

@DemonGiggle
Created April 12, 2017 04:50
Show Gist options
  • Save DemonGiggle/701f249227a098ada36497d545f89eb0 to your computer and use it in GitHub Desktop.
Save DemonGiggle/701f249227a098ada36497d545f89eb0 to your computer and use it in GitHub Desktop.
但事實證明是無法的,原因為動態產生的 class,在 sidekiq 環境中並無法得知
require "sidekiq/worker"
##
# 因為 Sidekiq::Worker 預設執行 perform,所以此 module 可以讓我們指定 sidekiq 要
# 執行的函示
#
# class Foo
# include SimpleWorker
#
# simple_worker_performer :bar
#
# def perform_worker
# FooWorker.perform_in(60)
# end
#
# def bar
# "blah blah"
# end
# end
#
# Foo.new.perform_worker
# => "blah blah"
#
module SimpleWorker
extend ActiveSupport::Concern
class_methods do
# 產生 #{self.name}Worker class,並且 include Sidekiq::Worker
def simple_worker_performer func_name
base_name = self.name
worker_klass = Class.new do
@base_name = base_name
@performer = func_name
class << self
include Sidekiq::Worker
attr_reader :performer, :base_name
end
def perform
# 因為此 class 的命名規則是 include 此 class 的 base name + Worker
# 所以我們可以知道當初的 base class 是誰
#klass = self.class.name.gsub(/Worker\z/, '')
klass = self.class.base_name.constantize
klass.new.send("#{self.class.performer}")
end
end
worker_klass.include(Sidekiq::Worker)
self.parent.const_set("#{self.name}Worker", worker_klass)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment