Rails - send all emails with a delay_job asynchronously

I use delayed_job , and I am very pleased with this (especially with the workless extension.)

But I would like to establish that ALL messages from my application are sent asynchronously.

Indeed, the solution offered for email programs

# without delayed_job
Notifier.signup(@user).deliver

# with delayed_job
Notifier.delay.signup(@user)

I am not happy because:

  • it is not easy to repair
  • letters sent from precious stones are not sent asynchronously ( devise , mailboxer )

I could use this kind of extension https://github.com/mhfs/devise-async , but I would rather find out a solution for the whole application right away.

ActionMailer, .deliver (, qaru.site/questions/744958/..., 4 , doc )?

Ruby 1.9 Rails 3.2 activerecord.

+3
2

Notifier :

class Notifier

  def self.deliver(message_type, *args)
    self.delay.send(message_type, *args)
  end

end

:

Notifier.deliver(:signup, @user)

, resque sidekiq.

0

ActiveJob , . - send_devise_notification , ,

class User < ApplicationRecord
  # whatever association you have here
  devise :database_authenticatable, :confirmable
  after_commit :send_pending_devise_notifications
  # whatever methods you have here

 protected
  def send_devise_notification(notification, *args)
    if new_record? || changed?
      pending_devise_notifications << [notification, args]
    else
      render_and_send_devise_message(notification, *args)
    end
  end

  private

  def send_pending_devise_notifications
    pending_devise_notifications.each do |notification, args|
      render_and_send_devise_message(notification, *args)
    end

    pending_devise_notifications.clear
  end

  def pending_devise_notifications
    @pending_devise_notifications ||= []
  end

  def render_and_send_devise_message(notification, *args)
    message = devise_mailer.send(notification, self, *args)

    # Deliver later with Active Job 'deliver_later'
    if message.respond_to?(:deliver_later)
      message.deliver_later
    # Remove once we move to Rails 4.2+ only, as 'deliver' is deprecated.
    elsif message.respond_to?(:deliver_now)
      message.deliver_now
    else
      message.deliver
    end
  end

end
0

All Articles