Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Active Job in Rails 4.2

Rick Liu
January 22, 2016

Active Job in Rails 4.2

Introduce basic usage of Active Job, including tests.

Rick Liu

January 22, 2016
Tweet

More Decks by Rick Liu

Other Decks in Programming

Transcript

  1. Active Job Active Job is an adapter layer on top

    of queuing systems. http://api.rubyonrails.org/classes/ActiveJob/QueueAdapters.html Resque, Delayed Job, Sidekiq, and more.
  2. Active Job invoke test_unit create test/jobs/daily_report_job_test.rb create app/jobs/daily_report_job.rb $ bin/rails

    generate job daily_report 1 class DailyReportJob < ActiveJob::Base 2 queue_as :default 3 4 def perform(*daily_events) 5 # Generate daily reports 6 end 7 end $ bin/rails generate job auth_center_signup --queue auth
  3. Active Job # Enqueue a job to be performed as

    soon as the queuing system is # free. # Enqueue a job to be performed 1 week from now. DailyReportJob.perform_later(event1, event 2) DailyReportJob.set(wait: 1.week).perform_later(event)
  4. Active Job # config/application.rb module YourApp class Application < Rails::Application

    # Be sure to have the adapter's gem in your Gemfile # and follow the adapter's specific installation # and deployment instructions. config.active_job.queue_adapter = :sidekiq end end
  5. Active Job Available callbacks • before_enqueue • around_enqueue • after_enqueue

    • before_perform • around_perform • after_perform
  6. Active Job 1 class DailyReportJob < ActiveJob::Base 2 queue_as :default

    3 4 rescue_from(ActiveRecord::RecordNotFound) do |exception| 5 # Do something with the exception 6 end 7 8 def perform(*args) 9 # Do something later 10 end 11 end Catch Exceptions
  7. Active Job Integrate Action Mailer # If you want to

    send the email now use #deliver_now UserMailer.welcome(@user).deliver_now # If you want to send the email through Active Job use #deliver_later UserMailer.welcome(@user).deliver_later
  8. Active Job A Basic Test Case 1 require 'test_helper' 2

    3 class BillingJobTest < ActiveJob::TestCase 4 test 'that account is charged' do 5 BillingJob.perform_now(account, product) 6 assert account.reload.charged_for?(product) 7 end 8 end By default, ActiveJob::TestCase will set the queue adapter to :test so that your jobs are performed inline.
  9. Active Job Custom Assertions 1 require 'test_helper' 2 3 class

    ProductTest < ActiveJob::TestCase 4 test 'billing job scheduling' do 5 assert_enqueued_with(job: BillingJob) do 6 product.charge(account) 7 end 8 end 9 end