From 2013dede296979172d6cae9e5e85045c3f0e9623 Mon Sep 17 00:00:00 2001 From: Bart de Water Date: Thu, 3 Aug 2017 10:32:18 -0400 Subject: Improve callback examples in Active Job guide [ci skip] The advice for symbol/block form is taken from the Active Record guides. --- guides/source/active_job_basics.md | 54 ++++++++++++++++++++++---------------- 1 file changed, 32 insertions(+), 22 deletions(-) (limited to 'guides/source/active_job_basics.md') diff --git a/guides/source/active_job_basics.md b/guides/source/active_job_basics.md index 443be77934..bde234bf84 100644 --- a/guides/source/active_job_basics.md +++ b/guides/source/active_job_basics.md @@ -260,40 +260,50 @@ backends you need to specify the queues to listen to. Callbacks --------- -Active Job provides hooks during the life cycle of a job. Callbacks allow you to -trigger logic during the life cycle of a job. - -### Available callbacks - -* `before_enqueue` -* `around_enqueue` -* `after_enqueue` -* `before_perform` -* `around_perform` -* `after_perform` - -### Usage +Active Job provides hooks to trigger logic during the life cycle of a job. Like +other callbacks in Rails, you can implement the callbacks as ordinary methods +and use a macro-style class method to register them as callbacks: ```ruby class GuestsCleanupJob < ApplicationJob queue_as :default - before_enqueue do |job| - # Do something with the job instance - end - - around_perform do |job, block| - # Do something before perform - block.call - # Do something after perform - end + around_perform :around_cleanup def perform # Do something later end + + private + def around_cleanup(job) + # Do something before perform + yield + # Do something after perform + end +end +``` + +The macro-style class methods can also receive a block. Consider using this +style if the code inside your block is so short that it fits in a single line. +For example, you could send metrics for every job enqueued: + +```ruby +class ApplicationJob + before_enqueue do |job| + $statsd.increment "#{job.name.underscore}.enqueue" + end end ``` +### Available callbacks + +* `before_enqueue` +* `around_enqueue` +* `after_enqueue` +* `before_perform` +* `around_perform` +* `after_perform` + Action Mailer ------------ -- cgit v1.2.3