Active Job in Rails

Total Blog Views: 46

Blog Status: publish

Created By: swaz_ahmed Created at: 06-12-2024

Tags: ror Active Job in Rails

In modern web applications, background job processing is essential for improving performance and user experience. Ruby on Rails offers a powerful tool for this purpose: Active Job. In this blog post, we’ll explore what Active Job is, how to set it up, and how to use it effectively in your Rails application.

What is Active Job?

Active Job is a framework for declaring jobs and making them run on a variety of queueing backends. It is included in Rails by default and provides a standardized interface for interacting with different queuing systems like Sidekiq, Resque, Delayed Job, and others.


 Why Use Active Job?

  • Decoupling: Move time-consuming tasks out of your request-response cycle, improving app responsiveness.

  • Retries and Failures: Handle job failures and retries gracefully.

  • Scheduling: Run tasks at specific times or intervals.

​​Scheduling: Run tasks at specific times or intervals.

        1. Adding a Queue Adapter

Rails supports several queue adapters. By default, it uses the :async adapter which is suitable for development but not for production.

For production, you might choose Sidekiq, Resque, or another adapter. For this guide, we'll use Sidekiq. First, add the Sidekiq gem to your Gemfile:

gem 'sidekiq'

Run bundle install to install the gem. 

        2. ​​Configuring Active Job

Next, configure your application to use Sidekiq by setting the queue adapter in config/application.rb:

 

# config/application.rb
module YourApp
  class Application < Rails::Application
    # Use Sidekiq for Active Job
    config.active_job.queue_adapter = :sidekiq
  end
end
 

Ensure you have Redis installed and running, as Sidekiq relies on Redis

        3. Creating a Job

Generate a new job using the Rails generator:

 

rails generate job Example

This creates a new job file in app/jobs/example_job.rb 

# app/jobs/example_job.rb
class ExampleJob < ApplicationJob
  queue_as :default
  def perform(*args)
    # Do something later
  end
end
 

        4. Enqueuing Jobs

You can enqueue jobs from anywhere in your application, such as controllers, models, or other jobs
# Enqueue a job to run immediately
ExampleJob.perform_later(argument1, argument2)

# Enqueue a job to run at a specific time
ExampleJob.set(wait_until: Date.tomorrow.noon).perform_later(argument1, argument2)
 

        5. Running Sidekiq

Start Sidekiq with the following command:

bundle exec sidekiq

Sidekiq will process jobs from the default queue. You can monitor the Sidekiq dashboard by navigating to /sidekiq in your browser. Make sure you mount the Sidekiq web interface in your config/routes.rb

 

# config/routes.rb
require 'sidekiq/web'
mount Sidekiq::Web => '/sidekiq'

 Example:- Sending Emails with Active Job

In this example, I'll demonstrate how to efficiently send welcome emails to new users using Active Job in a Ruby on Rails application.

1. Setup Mailer 

First, let's create a mailer to handle the email functionality:

 

rails generate mailer UserMailer

Edit the generated mailer file to define the email action:

 

# app/mailers/user_mailer.rb
class UserMailer < ApplicationMailer
  default from: '[email protected]'

  def welcome_email(user)
    @user = user
    @url  = 'http://example.com/login'
    mail(to: @user.email, subject: 'Welcome to My Awesome Site')
  end
end

 

2. Create the Job

Next, generate a job for sending the welcome email:

 

rails generate job SendWelcomeEmail

Edit the job file to perform the mailer action:

 

# app/jobs/send_welcome_email_job.rb
class SendWelcomeEmailJob < ApplicationJob
  queue_as :default

  def perform(user)
    UserMailer.welcome_email(user).deliver_now
  end
end

 

3. Enqueue the Job

Enqueue the job when a new user signs up:

 

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    @user = User.new(user_params)

    if @user.save
      SendWelcomeEmailJob.perform_later(@user)
      redirect_to @user, notice: 'User was successfully created.'
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end
end

 

4. Queueing a Job

To queue the job for sending the welcome email, you can use the perform_later method provided by Active Job. This method schedules the job to be executed asynchronously in the background.

 

# app/controllers/users_controller.rb
class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      # Queue the SendWelcomeEmailJob
      SendWelcomeEmailJob.perform_later(@user)
      redirect_to @user, notice: 'User was successfully created.'
    else
      render :new
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end
end

 

5. Testing

When testing the sending of welcome emails, it's important to ensure that the emails are being sent correctly and that the job is enqueued as expected. You can use testing frameworks like RSpec or Minitest to write test cases for this functionality.

Here's an example using RSpec:

 

# spec/jobs/send_welcome_email_job_spec.rb
require 'rails_helper'
RSpec.describe SendWelcomeEmailJob, type: :job do

  it "queues the job" do
    ActiveJob::Base.queue_adapter = :test
    expect {
      SendWelcomeEmailJob.perform_later(User.new(email: "[email protected]"))
    }.to have_enqueued_job
  end

  it "sends welcome email" do
    user = User.create(name: "Test User", email: "[email protected]", password: "password", password_confirmation: "password")
    expect {
      SendWelcomeEmailJob.perform_now(user)
    }.to change { ActionMailer::Base.deliveries.count }.by(1)
  end
end

 

These tests verify that the job is enqueued properly and that the welcome email is sent when the job is performed. You can adjust the test cases according to your specific requirements and testing framework preferences.

Conclusion

Integrating Active Job in Rails applications allows for efficient handling of background tasks, enhancing both performance and user experience. By leveraging queue adapters like Sidekiq, you can seamlessly manage and monitor background jobs. Implement Active Job in your Rails projects today to experience these benefits firsthand.


swaz_ahmed

I am swaz_ahmed blogger on shadbox. I am influencer,content writer,author and publisher. Feel free to ask me any question and suggestions.



Comments



Buy traffic for your website

About Shadbox

we have the “Get things executed” lifestyle at our place of work. There are not any excuses, no if’s or however’s in our dictionary. committed to navigating the ship of creativity to create cell answers, we resolve the real-lifestyles troubles of our clients and their clients. Our passion for work has won us many awards, year after 12 months.

Services

Downloads