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

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top