Rails 3: Trying to extend Action Mailer with a module

守給你的承諾、 提交于 2020-01-05 08:11:32

问题


Trying to rewrite an old alias_method_chain to add a filter on outgoing emails, and it isn't working. I'm pretty sure I've leaving something out/missing something, but I don't know what.

This file is in /lib/outgoing_mail_filter.rb, which is loaded with config/initializers/required.rb

Here's the old code that worked under 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

And here's my current attempt at re-writing it:

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

When I run my tests, it doesn't even look like this is being called or anything. Any help is appreciated


回答1:


I'm using mail_safe to rewrite emails in the development environment, highly recommended. You could look into it for inspiration if it doesn't fit your bill, the code is very simple.

The following code is extracted from /lib/mail_safe/rails3_hook.rb and should do what you want:

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

Alternate version, registering with ActionMailer::Base instead of Mail (thanks to Kevin Whitaker for letting me know it's possible):

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


来源:https://stackoverflow.com/questions/8328773/rails-3-trying-to-extend-action-mailer-with-a-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!