2

Is it possible to have a mail Observer that handle only a specific Mailer ?

So that we can possibly have different mailer - mail-observer pair that work together to handle task after their mail has been sent.

For instance one mail-obser could delete temporary generated attached-files, while another could log the sending of some specific type of message (of a specific mailer).

If it is possible, could you illustrate how do we make the "connection" works between the mailer and the mail-observer classes ?

Many Thanks

Douglas
  • 5,229
  • 3
  • 43
  • 54

1 Answers1

4

I found some example telling to put this into any file in config/initializers/ :

ActionMailer::Base.register_observer(MyMailObserver)

However this was a global setting.

I found the solution after digging into api. I realized register_observer() was a class method, so I tried to apply it on my app/mailer/report_mailer.rb class :

class ReportMailer < ActionMailer::Base
  default from: "my_email@my_domaine.com"

  def monthly_report(user, report_name, file_name, file_path)
    @user = user
    @report_name = report_name
    attachments[file_name] = File.read(file_path)
    mail(:to => user.email, :subject => "Generated report for #{report_name} (automatic message)")
  end
end

I managed to apply it with the initialization of my observer for my mailer in config/initializers/my_mailer_observer_initializer.rb :

ReportMailer.register_observer(MyMailObserver)

So I got MyMailerObserver in relationship with my ReportMailer class and no other Mailer class.

Douglas
  • 5,229
  • 3
  • 43
  • 54
  • This is not working for me. All mailers triggers the observer. https://stackoverflow.com/questions/44902707/register-an-observer-to-only-one-mailer – Pedro Adame Vergara Jul 04 '17 at 10:00