mirror of
https://github.com/mperham/sidekiq.git
synced 2022-11-09 13:52:34 -05:00
Implement ActiveJob-style set
, fixes #2780
The `set` method allows the user to dynamically override worker options without having to drop down to the Sidekiq::Client API, e.g. MyWorker.set(queue: 'foo').perform_async(1)
This commit is contained in:
parent
d191ac45a3
commit
d6538b0b4f
2 changed files with 50 additions and 1 deletions
|
@ -50,6 +50,11 @@ module Sidekiq
|
|||
raise ArgumentError, "Do not call .delay_until on a Sidekiq::Worker class, call .perform_at"
|
||||
end
|
||||
|
||||
def set(options)
|
||||
Thread.current[:sidekiq_worker_set] = options
|
||||
self
|
||||
end
|
||||
|
||||
def perform_async(*args)
|
||||
client_push('class' => self, 'args' => args)
|
||||
end
|
||||
|
@ -97,7 +102,13 @@ module Sidekiq
|
|||
|
||||
def client_push(item) # :nodoc:
|
||||
pool = Thread.current[:sidekiq_via_pool] || get_sidekiq_options['pool'] || Sidekiq.redis_pool
|
||||
Sidekiq::Client.new(pool).push(item.stringify_keys)
|
||||
hash = if Thread.current[:sidekiq_worker_set]
|
||||
x, Thread.current[:sidekiq_worker_set] = Thread.current[:sidekiq_worker_set], nil
|
||||
x.stringify_keys.merge(item.stringify_keys)
|
||||
else
|
||||
item.stringify_keys
|
||||
end
|
||||
Sidekiq::Client.new(pool).push(hash)
|
||||
end
|
||||
|
||||
end
|
||||
|
|
|
@ -191,4 +191,42 @@ class TestClient < Sidekiq::Test
|
|||
conn.verify
|
||||
end
|
||||
end
|
||||
|
||||
describe 'Sidekiq::Worker#set' do
|
||||
class SetWorker
|
||||
include Sidekiq::Worker
|
||||
sidekiq_options queue: :foo, 'retry': 12
|
||||
end
|
||||
|
||||
def setup
|
||||
Sidekiq.redis {|c| c.flushdb }
|
||||
end
|
||||
|
||||
it 'allows option overrides' do
|
||||
q = Sidekiq::Queue.new('bar')
|
||||
assert_equal 0, q.size
|
||||
assert SetWorker.set(queue: :bar).perform_async(1)
|
||||
job = q.first
|
||||
assert_equal 'bar', job['queue']
|
||||
assert_equal 12, job['retry']
|
||||
end
|
||||
|
||||
it 'handles symbols and strings' do
|
||||
q = Sidekiq::Queue.new('bar')
|
||||
assert_equal 0, q.size
|
||||
assert SetWorker.set('queue' => 'bar', :retry => 11).perform_async(1)
|
||||
job = q.first
|
||||
assert_equal 'bar', job['queue']
|
||||
assert_equal 11, job['retry']
|
||||
|
||||
q.clear
|
||||
assert SetWorker.perform_async(1)
|
||||
assert_equal 0, q.size
|
||||
|
||||
q = Sidekiq::Queue.new('foo')
|
||||
job = q.first
|
||||
assert_equal 'foo', job['queue']
|
||||
assert_equal 12, job['retry']
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue