1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/activejob/lib/active_job/queue_adapters/test_adapter.rb

82 lines
2.3 KiB
Ruby
Raw Normal View History

2017-07-09 13:49:52 -04:00
# frozen_string_literal: true
2014-08-26 16:08:49 -04:00
module ActiveJob
module QueueAdapters
2014-09-21 16:20:23 -04:00
# == Test adapter for Active Job
#
# The test adapter should be used only in testing. Along with
# <tt>ActiveJob::TestCase</tt> and <tt>ActiveJob::TestHelper</tt>
# it makes a great tool to test your Rails application.
#
# To use the test adapter set queue_adapter config to +:test+.
#
# Rails.application.config.active_job.queue_adapter = :test
2014-08-26 16:08:49 -04:00
class TestAdapter
attr_accessor(:perform_enqueued_jobs, :perform_enqueued_at_jobs, :filter, :reject, :queue)
attr_writer(:enqueued_jobs, :performed_jobs)
2014-08-26 16:08:49 -04:00
# Provides a store of all the enqueued jobs with the TestAdapter so you can check them.
def enqueued_jobs
@enqueued_jobs ||= []
end
# Provides a store of all the performed jobs with the TestAdapter so you can check them.
def performed_jobs
@performed_jobs ||= []
end
2014-08-26 16:08:49 -04:00
def enqueue(job) #:nodoc:
return if filtered?(job)
job_data = job_to_hash(job)
perform_or_enqueue(perform_enqueued_jobs, job, job_data)
end
def enqueue_at(job, timestamp) #:nodoc:
return if filtered?(job)
job_data = job_to_hash(job, at: timestamp)
perform_or_enqueue(perform_enqueued_at_jobs, job, job_data)
end
private
def job_to_hash(job, extras = {})
{ job: job.class, args: job.serialize.fetch("arguments"), queue: job.queue_name }.merge!(extras)
end
def perform_or_enqueue(perform, job, job_data)
if perform
performed_jobs << job_data
Base.execute job.serialize
else
enqueued_jobs << job_data
end
end
def filtered?(job)
filtered_queue?(job) || filtered_job_class?(job)
end
def filtered_queue?(job)
if queue
job.queue_name != queue.to_s
end
end
def filtered_job_class?(job)
if filter
!filter_as_proc(filter).call(job)
elsif reject
filter_as_proc(reject).call(job)
end
end
def filter_as_proc(filter)
return filter if filter.is_a?(Proc)
->(job) { Array(filter).include?(job.class) }
end
2014-08-26 16:08:49 -04:00
end
end
end