rlhh
rlhh

Reputation: 903

Sidekiq Delayed Mailer with variable method name

Just for some context: I have 3 different methods called welcome_email(user_id), banned_email(user_id) and upgrade_email((user_id) in a file called notification_mailer.rb.

Is there a way where I can call the different methods differently based on a string? (aka a string variable as part of a method call).

For example: I know I can do

NotificationMailer.send("#{email_type}_email", user.id)

to call

NotificationMailer.welcome_email(user.id) / NotificationMailer.banned_email(user.id) / NotificationMailer.upgrade_email(user.id)

but how do I call (adding in the delay part)

Notification.delay.welcome_email(user.id) ?

Can I just do NotificationMailer.delay.send("#{email_type}_email", user.id)?

Upvotes: 0

Views: 397

Answers (1)

Winfield
Winfield

Reputation: 19145

Assuming you have a NotificationMailer object that's an ActionMailer with a variety of different notification methods that each take a user, you can write a simple Sidekiq job to send your e-mails in the background:

class NotificationWorker
  include Sidekiq::Worker

  def perform(notification_type, user_id)
    user = User.find(user_id)
    NotificationMailer.send(notification_type, user).deliver
  end
end

Now that you have this, you can enqueue an async notification e-mail by calling that job:

NotificationWorker.perform_async('welcome_email', user.id)

Upvotes: 1

Related Questions