2011-11-30 363 views
1

嘗試重寫舊的alias_method_chain以在傳出電子郵件上添加篩選器,但它不起作用。我很確定我已經遺漏了一些東西,但我不知道是什麼。Rails 3:嘗試使用模塊擴展Action Mailer

此文件是/lib/outgoing_mail_filter.rb,其中裝有配置/初始化/ required.rb

這裏的舊代碼,根據梁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 

當我運行我的測試時,它甚至看起來不像是被調用或任何東西。任何幫助表示讚賞

回答

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註冊(感謝凱文·惠特克讓我知道這是可能的):

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 
+0

以下示例結束,但註冊ActionMailer :: Base而不是郵件。謝謝! –