Rails 3:尝试使用模块扩展Action Mailer

时间:2011-11-30 15:49:46

标签: ruby-on-rails-3 module actionmailer

尝试重写旧的alias_method_chain以在外发电子邮件上添加过滤器,但它无效。我很确定我会遗漏一些东西/遗漏一些东西,但我不知道是什么。

此文件位于/lib/outgoing_mail_filter.rb中,该文件已加载config / initializers / required.rb

这是在Rails 2下运行的旧代码:

class ActionMailer::Base
  def deliver_with_recipient_filter!(mail = @mail) 
    unless 'production' == Rails.env
      mail.to = mail.to.to_a.delete_if do |to| 
        !(to.ends_with?('some_domain.com'))
      end
    end
    unless mail.to.blank?
      deliver_without_recipient_filter!(mail)
    end
  end
  alias_method_chain 'deliver!'.to_sym, :recipient_filter
end

这是我目前重写它的尝试:

class ActionMailer::Base
  module RecipientFilter
    def deliver(mail = @mail) 
      super
      unless 'production' == Rails.env
        mail.to = mail.to.to_a.delete_if do |to| 
          !(to.ends_with?('some_domain.com'))
        end
      end
      unless mail.to.blank?
        deliver(mail)
      end    
    end
  end

  include RecipientFilter
end

当我运行我的测试时,它甚至看起来都没有被调用或任何东西。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

我正在使用mail_safe来重写开发环境中的电子邮件,强烈推荐。如果它不适合您的账单,您可以查看它的灵感,代码非常简单。

以下代码摘自/lib/mail_safe/rails3_hook.rb,应该按照您的意愿行事:

require 'mail'

module MailSafe
  class MailInterceptor
    def self.delivering_email(mail)
      # replace the following line with your code
      # and don't forget to return the mail object at the end
      MailSafe::AddressReplacer.replace_external_addresses(mail) if mail
    end

    ::Mail.register_interceptor(self)
  end
end

备用版本,使用ActionMailer::Base而不是Mail注册(感谢Kevin Whitaker让我知道这是可能的):

module MailSafe
  class MailInterceptor
    def self.delivering_email(mail)
      # replace the following line with your code
      # and don't forget to return the mail object at the end
      MailSafe::AddressReplacer.replace_external_addresses(mail) if mail
    end

    ::ActionMailer::Base.register_interceptor(self)
  end
end